Skip to content

Commit c41a320

Browse files
committed
Add custom formatter for RichHandler to output miliseconds
The default .%f handling in RichHandler gives microseconds and strftime does not provide a milisecond format string.
1 parent 55efb20 commit c41a320

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

src/log.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,12 @@
55
import os
66
import sys
77
import typing as t
8+
from datetime import datetime
89
from functools import lru_cache
910

1011
import uvicorn.config
1112
from pydantic.v1.utils import deep_update
13+
from rich.text import Text
1214

1315
from constants import (
1416
DEFAULT_LOG_FORMAT,
@@ -19,6 +21,11 @@
1921
)
2022

2123

24+
def _ms_time_format(dt: datetime) -> Text:
25+
"""Format datetime object with zero padded milliseconds."""
26+
return Text(dt.strftime("%Y-%m-%d %H:%M:%S.") + f"{dt.microsecond // 1000:03d}")
27+
28+
2229
def resolve_log_level() -> int:
2330
"""
2431
Resolve and validate the log level from environment variable.
@@ -87,7 +94,7 @@ def setup_logging() -> dict[t.Any, t.Any]:
8794
"rich": {
8895
"()": "rich.logging.RichHandler",
8996
"show_time": True,
90-
"log_time_format": "%Y-%m-%d %H:%M:%S.%f",
97+
"log_time_format": _ms_time_format,
9198
"level": log_level,
9299
},
93100
},

0 commit comments

Comments
 (0)