53 lines
2.0 KiB
Python
53 lines
2.0 KiB
Python
"""JSON-lines logging to stdout. Logs never contain message texts or request bodies.
|
|
|
|
Lab 6: every line written inside an active span carries its trace_id/span_id (the same ids the
|
|
OTLP copy of the record has in Loki), so `docker compose logs` can be joined with Tempo too."""
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
import json
|
|
import logging
|
|
import os
|
|
import sys
|
|
|
|
from . import telemetry
|
|
|
|
|
|
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(),
|
|
}
|
|
ids = telemetry.current_ids()
|
|
if ids:
|
|
entry["trace_id"], entry["span_id"] = ids
|
|
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
|
|
|
|
|
|
def configure_early() -> None:
|
|
"""Before Settings exist (lab 7: secrets are fetched from OpenBao while the settings load, and
|
|
those log lines must not be lost). Settings.from_env() validates LOG_LEVEL properly later."""
|
|
raw = os.environ.get("LOG_LEVEL", "info").strip().lower()
|
|
configure(raw if raw in {"debug", "info", "warning", "error"} else "info")
|