|
| 1 | +""" |
| 2 | +Structured logging utilities for CodeFlow applications. |
| 3 | +
|
| 4 | +Provides JSON-formatted structured logging with correlation IDs and |
| 5 | +contextual information. This is a portable version that doesn't depend |
| 6 | +on codeflow_engine internals. |
| 7 | +""" |
| 8 | + |
| 9 | +import json |
| 10 | +import logging |
| 11 | +import sys |
| 12 | +from datetime import datetime, timezone |
| 13 | +from pathlib import Path |
| 14 | +from typing import Any |
| 15 | + |
| 16 | + |
| 17 | +class JsonFormatter(logging.Formatter): |
| 18 | + """JSON formatter for structured logging.""" |
| 19 | + |
| 20 | + def __init__(self, service_name: str = "codeflow"): |
| 21 | + """ |
| 22 | + Initialize the JSON formatter. |
| 23 | +
|
| 24 | + Args: |
| 25 | + service_name: Name of the service for log identification |
| 26 | + """ |
| 27 | + super().__init__() |
| 28 | + self.service_name = service_name |
| 29 | + |
| 30 | + def format(self, record: logging.LogRecord) -> str: |
| 31 | + """ |
| 32 | + Format log record as JSON. |
| 33 | +
|
| 34 | + Args: |
| 35 | + record: Log record to format |
| 36 | +
|
| 37 | + Returns: |
| 38 | + JSON-formatted log string |
| 39 | + """ |
| 40 | + log_data: dict[str, Any] = { |
| 41 | + "timestamp": datetime.now(timezone.utc).isoformat(), |
| 42 | + "level": record.levelname, |
| 43 | + "service": self.service_name, |
| 44 | + "component": record.name, |
| 45 | + "message": record.getMessage(), |
| 46 | + "module": record.module, |
| 47 | + "function": record.funcName, |
| 48 | + "line": record.lineno, |
| 49 | + } |
| 50 | + |
| 51 | + # Add extra fields from record |
| 52 | + if hasattr(record, "request_id"): |
| 53 | + log_data["request_id"] = record.request_id |
| 54 | + if hasattr(record, "user_id"): |
| 55 | + log_data["user_id"] = record.user_id |
| 56 | + if hasattr(record, "duration_ms"): |
| 57 | + log_data["duration_ms"] = record.duration_ms |
| 58 | + if hasattr(record, "correlation_id"): |
| 59 | + log_data["correlation_id"] = record.correlation_id |
| 60 | + |
| 61 | + # Add exception info if present |
| 62 | + if record.exc_info: |
| 63 | + log_data["exception"] = self.formatException(record.exc_info) |
| 64 | + log_data["exception_type"] = ( |
| 65 | + record.exc_info[0].__name__ if record.exc_info[0] else None |
| 66 | + ) |
| 67 | + |
| 68 | + # Add any additional extra fields |
| 69 | + excluded_keys = { |
| 70 | + "name", |
| 71 | + "msg", |
| 72 | + "args", |
| 73 | + "created", |
| 74 | + "filename", |
| 75 | + "funcName", |
| 76 | + "levelname", |
| 77 | + "levelno", |
| 78 | + "lineno", |
| 79 | + "module", |
| 80 | + "msecs", |
| 81 | + "message", |
| 82 | + "pathname", |
| 83 | + "process", |
| 84 | + "processName", |
| 85 | + "relativeCreated", |
| 86 | + "thread", |
| 87 | + "threadName", |
| 88 | + "exc_info", |
| 89 | + "exc_text", |
| 90 | + "stack_info", |
| 91 | + } |
| 92 | + for key, value in record.__dict__.items(): |
| 93 | + if key not in excluded_keys and not key.startswith("_"): |
| 94 | + log_data[key] = value |
| 95 | + |
| 96 | + return json.dumps(log_data, default=str) |
| 97 | + |
| 98 | + |
| 99 | +class TextFormatter(logging.Formatter): |
| 100 | + """Human-readable text formatter for development.""" |
| 101 | + |
| 102 | + def format(self, record: logging.LogRecord) -> str: |
| 103 | + """ |
| 104 | + Format log record as human-readable text. |
| 105 | +
|
| 106 | + Args: |
| 107 | + record: Log record to format |
| 108 | +
|
| 109 | + Returns: |
| 110 | + Formatted log string |
| 111 | + """ |
| 112 | + timestamp = datetime.fromtimestamp(record.created, tz=timezone.utc).strftime( |
| 113 | + "%Y-%m-%d %H:%M:%S UTC" |
| 114 | + ) |
| 115 | + level = record.levelname.ljust(8) |
| 116 | + component = record.name |
| 117 | + message = record.getMessage() |
| 118 | + |
| 119 | + # Build context string |
| 120 | + context_parts = [] |
| 121 | + if hasattr(record, "request_id"): |
| 122 | + context_parts.append(f"request_id={record.request_id}") |
| 123 | + if hasattr(record, "user_id"): |
| 124 | + context_parts.append(f"user_id={record.user_id}") |
| 125 | + if hasattr(record, "duration_ms"): |
| 126 | + context_parts.append(f"duration={record.duration_ms}ms") |
| 127 | + |
| 128 | + context = f" [{', '.join(context_parts)}]" if context_parts else "" |
| 129 | + |
| 130 | + log_line = f"{timestamp} | {level} | {component} | {message}{context}" |
| 131 | + |
| 132 | + # Add exception if present |
| 133 | + if record.exc_info: |
| 134 | + log_line += f"\n{self.formatException(record.exc_info)}" |
| 135 | + |
| 136 | + return log_line |
| 137 | + |
| 138 | + |
| 139 | +def setup_logging( |
| 140 | + level: str = "INFO", |
| 141 | + format_type: str = "json", |
| 142 | + output: str = "stdout", |
| 143 | + log_file: str | Path | None = None, |
| 144 | + service_name: str = "codeflow", |
| 145 | +) -> None: |
| 146 | + """ |
| 147 | + Configure structured logging. |
| 148 | +
|
| 149 | + Args: |
| 150 | + level: Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
| 151 | + format_type: Format type ('json' or 'text') |
| 152 | + output: Output destination ('stdout', 'file', or 'both') |
| 153 | + log_file: Path to log file (required if output is 'file' or 'both') |
| 154 | + service_name: Name of the service for log identification |
| 155 | + """ |
| 156 | + root_logger = logging.getLogger() |
| 157 | + root_logger.setLevel(getattr(logging, level.upper(), logging.INFO)) |
| 158 | + root_logger.handlers.clear() |
| 159 | + |
| 160 | + if format_type == "json": |
| 161 | + formatter = JsonFormatter(service_name=service_name) |
| 162 | + else: |
| 163 | + formatter = TextFormatter() |
| 164 | + |
| 165 | + if output in ("stdout", "both"): |
| 166 | + stdout_handler = logging.StreamHandler(sys.stdout) |
| 167 | + stdout_handler.setFormatter(formatter) |
| 168 | + stdout_handler.setLevel(getattr(logging, level.upper(), logging.INFO)) |
| 169 | + root_logger.addHandler(stdout_handler) |
| 170 | + |
| 171 | + if output in ("file", "both"): |
| 172 | + if log_file is None: |
| 173 | + raise ValueError("log_file is required when output is 'file' or 'both'") |
| 174 | + log_path = Path(log_file) |
| 175 | + log_path.parent.mkdir(parents=True, exist_ok=True) |
| 176 | + |
| 177 | + file_handler = logging.FileHandler(log_file) |
| 178 | + file_handler.setFormatter(formatter) |
| 179 | + file_handler.setLevel(getattr(logging, level.upper(), logging.INFO)) |
| 180 | + root_logger.addHandler(file_handler) |
| 181 | + |
| 182 | + # Reduce noise from third-party libraries |
| 183 | + logging.getLogger("urllib3").setLevel(logging.WARNING) |
| 184 | + logging.getLogger("httpx").setLevel(logging.WARNING) |
| 185 | + logging.getLogger("asyncio").setLevel(logging.WARNING) |
| 186 | + |
| 187 | + |
| 188 | +def get_logger(name: str) -> logging.Logger: |
| 189 | + """ |
| 190 | + Get a logger instance for a module. |
| 191 | +
|
| 192 | + Args: |
| 193 | + name: Logger name (typically __name__) |
| 194 | +
|
| 195 | + Returns: |
| 196 | + Logger instance |
| 197 | + """ |
| 198 | + return logging.getLogger(name) |
| 199 | + |
| 200 | + |
| 201 | +def log_with_context( |
| 202 | + logger: logging.Logger, |
| 203 | + level: int, |
| 204 | + message: str, |
| 205 | + **context: Any, |
| 206 | +) -> None: |
| 207 | + """ |
| 208 | + Log a message with additional context. |
| 209 | +
|
| 210 | + Args: |
| 211 | + logger: Logger instance |
| 212 | + level: Log level (logging.INFO, etc.) |
| 213 | + message: Log message |
| 214 | + **context: Additional context fields |
| 215 | + """ |
| 216 | + logger.log(level, message, extra=context) |
0 commit comments