-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging.py
More file actions
54 lines (38 loc) · 1.75 KB
/
logging.py
File metadata and controls
54 lines (38 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""Structured JSON logging with OpenTelemetry trace correlation."""
from __future__ import annotations
import json
import logging
import os
import sys
from datetime import UTC, datetime
class _JSONFormatter(logging.Formatter):
"""Format log records as single-line JSON with OTel trace context."""
def format(self, record: logging.LogRecord) -> str:
entry: dict[str, str | int | float] = {
"timestamp": datetime.fromtimestamp(record.created, tz=UTC).isoformat(),
"level": record.levelname,
"module": record.module,
"message": record.getMessage(),
}
# Trace context injected by OTel logging instrumentation
entry["trace_id"] = getattr(record, "otelTraceID", "0")
entry["span_id"] = getattr(record, "otelSpanID", "0")
return json.dumps(entry, default=str)
def setup_logging(level: str | None = None) -> None:
"""Configure Python logging with structured JSON output and OTel correlation.
Reads ``LOG_LEVEL`` from the environment if *level* is not provided.
Args:
level: Logging level name (e.g. "INFO", "DEBUG"). Falls back to the
``LOG_LEVEL`` environment variable, then to ``"INFO"``.
"""
from opentelemetry.instrumentation.logging import LoggingInstrumentor
resolved_level = (level if level else os.getenv("LOG_LEVEL", "INFO")).upper()
# Instrument stdlib logging so trace/span IDs are injected
LoggingInstrumentor().instrument(set_logging_format=False)
root = logging.getLogger()
root.setLevel(resolved_level)
# Remove existing handlers to avoid duplicate output
root.handlers.clear()
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(_JSONFormatter())
root.addHandler(handler)