forked from mtusi2026/mtusi2026lab2
Исходная точка lab2: код из solution/bvt2302-bodanyuk лабы 1, коммит 472c1bd. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
37 lines
1.3 KiB
Python
37 lines
1.3 KiB
Python
"""JSON-lines logging to stdout. Logs never contain message texts or request bodies."""
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
import json
|
|
import logging
|
|
import sys
|
|
|
|
|
|
class JsonFormatter(logging.Formatter):
|
|
def format(self, record: logging.LogRecord) -> str:
|
|
entry = {
|
|
"ts": dt.datetime.fromtimestamp(record.created, dt.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
|
"level": record.levelname.lower(),
|
|
"logger": record.name,
|
|
"event": record.getMessage(),
|
|
}
|
|
fields = getattr(record, "fields", None)
|
|
if fields:
|
|
entry.update(fields)
|
|
if record.exc_info:
|
|
# Stack traces go only to the server log, never to the HTTP client.
|
|
entry["exception"] = self.formatException(record.exc_info)
|
|
return json.dumps(entry, ensure_ascii=False)
|
|
|
|
|
|
def configure(level: str) -> None:
|
|
handler = logging.StreamHandler(sys.stdout)
|
|
handler.setFormatter(JsonFormatter())
|
|
root = logging.getLogger()
|
|
root.handlers[:] = [handler]
|
|
root.setLevel(level.upper())
|
|
# uvicorn's own access log is disabled; our middleware writes one line per request.
|
|
for name in ("uvicorn", "uvicorn.error"):
|
|
logging.getLogger(name).handlers[:] = []
|
|
logging.getLogger(name).propagate = True
|