A logging formatter which formats record with :func:`datetime.datetime.strftime` formatter instead of :func:`time.strftime` in case of microseconds in format string.
| 59 | |
| 60 | |
| 61 | class DatetimeFormatter(logging.Formatter): |
| 62 | """A logging formatter which formats record with |
| 63 | :func:`datetime.datetime.strftime` formatter instead of |
| 64 | :func:`time.strftime` in case of microseconds in format string. |
| 65 | """ |
| 66 | |
| 67 | def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: |
| 68 | if datefmt and "%f" in datefmt: |
| 69 | ct = self.converter(record.created) |
| 70 | tz = timezone(timedelta(seconds=ct.tm_gmtoff), ct.tm_zone) |
| 71 | # Construct `datetime.datetime` object from `struct_time` |
| 72 | # and msecs information from `record` |
| 73 | # Using int() instead of round() to avoid it exceeding 1_000_000 and causing a ValueError (#11861). |
| 74 | dt = datetime(*ct[0:6], microsecond=int(record.msecs * 1000), tzinfo=tz) |
| 75 | return dt.strftime(datefmt) |
| 76 | # Use `logging.Formatter` for non-microsecond formats |
| 77 | return super().formatTime(record, datefmt) |
| 78 | |
| 79 | |
| 80 | class ColoredLevelFormatter(DatetimeFormatter): |
no outgoing calls
no test coverage detected