Formats log records as single-line JSON objects.
| 10 | |
| 11 | |
| 12 | class JSONFormatter(logging.Formatter): |
| 13 | """Formats log records as single-line JSON objects.""" |
| 14 | |
| 15 | def format(self, record: logging.LogRecord) -> str: |
| 16 | entry: dict[str, Any] = { |
| 17 | "timestamp": datetime.fromtimestamp( |
| 18 | record.created, tz=timezone.utc |
| 19 | ).isoformat(), |
| 20 | "level": record.levelname, |
| 21 | "logger": record.name, |
| 22 | "message": record.getMessage(), |
| 23 | } |
| 24 | # Capture extra structured fields set via `extra={}` on log calls |
| 25 | for key in ("stage", "session_id", "model", "tokens", "latency_ms", |
| 26 | "error_type", "agent"): |
| 27 | val = getattr(record, key, None) |
| 28 | if val is not None: |
| 29 | entry[key] = val |
| 30 | if record.exc_info and record.exc_info[1]: |
| 31 | entry["exception"] = self.formatException(record.exc_info) |
| 32 | return json.dumps(entry, ensure_ascii=False, default=str) |
| 33 | |
| 34 | |
| 35 | def setup_logging( |