|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import logging.config |
| 4 | +import sys |
| 5 | +from datetime import datetime, timezone |
| 6 | +from pathlib import Path |
| 7 | +from typing import Any, Dict |
| 8 | + |
| 9 | + |
| 10 | +class JsonFormatter(logging.Formatter): |
| 11 | + """Custom JSON formatter for structured logging. |
| 12 | +
|
| 13 | + Formats log records as JSON objects with consistent structure including |
| 14 | + timestamp, level, logger name, module, line number, message and exceptions. |
| 15 | + """ |
| 16 | + |
| 17 | + def format(self, record: logging.LogRecord) -> str: |
| 18 | + """Format the log record as a JSON string. |
| 19 | +
|
| 20 | + Args: |
| 21 | + record: The log record to format. |
| 22 | +
|
| 23 | + Returns: |
| 24 | + JSON-formatted string with log information. |
| 25 | + """ |
| 26 | + log_data: Dict[str, Any] = { |
| 27 | + "timestamp": datetime.now(timezone.utc).isoformat(), |
| 28 | + "level": record.levelname, |
| 29 | + "logger": record.name, |
| 30 | + "module": record.module, |
| 31 | + "function": record.funcName, |
| 32 | + "line": record.lineno, |
| 33 | + "message": record.getMessage(), |
| 34 | + } |
| 35 | + if record.exc_info: |
| 36 | + log_data["exception"] = self.formatException(record.exc_info) |
| 37 | + # core/logging.py |
| 38 | + if hasattr(record, "request_id"): |
| 39 | + log_data["request_id"] = getattr(record, "request_id") |
| 40 | + if hasattr(record, "method"): |
| 41 | + log_data["method"] = getattr(record, "method") |
| 42 | + if hasattr(record, "path"): |
| 43 | + log_data["path"] = getattr(record, "path") |
| 44 | + if hasattr(record, "client_host"): |
| 45 | + log_data["client_host"] = getattr(record, "client_host") |
| 46 | + if hasattr(record, "query_params"): |
| 47 | + log_data["query_params"] = getattr(record, "query_params") |
| 48 | + if hasattr(record, "status_code"): |
| 49 | + log_data["status_code"] = getattr(record, "status_code") |
| 50 | + if hasattr(record, "duration_ms"): |
| 51 | + log_data["duration_ms"] = getattr(record, "duration_ms") |
| 52 | + # all routers |
| 53 | + return json.dumps(log_data, default=str) |
| 54 | + |
| 55 | + |
| 56 | +LOG_DIR = Path("/var/log/backend") |
| 57 | +if "pytest" in sys.modules: |
| 58 | + LOG_DIR = Path("/tmp/logs") |
| 59 | +LOG_DIR.mkdir(exist_ok=True) |
| 60 | + |
| 61 | +LOGGING_CONFIG = { |
| 62 | + "version": 1, |
| 63 | + "disable_existing_loggers": False, |
| 64 | + "formatters": { |
| 65 | + "default": { |
| 66 | + "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s", |
| 67 | + "datefmt": "%Y-%m-%d %H:%M:%S", |
| 68 | + }, |
| 69 | + "json": { |
| 70 | + "()": JsonFormatter, |
| 71 | + }, |
| 72 | + }, |
| 73 | + "handlers": { |
| 74 | + "console": { |
| 75 | + "class": "logging.StreamHandler", |
| 76 | + "level": "INFO", |
| 77 | + "formatter": "default", |
| 78 | + "stream": sys.stdout, |
| 79 | + }, |
| 80 | + "console_json": { |
| 81 | + "class": "logging.StreamHandler", |
| 82 | + "level": "DEBUG", |
| 83 | + "formatter": "json", |
| 84 | + "stream": sys.stdout, |
| 85 | + }, |
| 86 | + "file": { |
| 87 | + "class": "logging.handlers.RotatingFileHandler", |
| 88 | + "level": "INFO", |
| 89 | + "formatter": "json", |
| 90 | + "filename": str(LOG_DIR / "app.log"), |
| 91 | + "maxBytes": 10485760, # 10MB |
| 92 | + "backupCount": 5, |
| 93 | + "encoding": "utf-8", |
| 94 | + }, |
| 95 | + "error_file": { |
| 96 | + "class": "logging.handlers.RotatingFileHandler", |
| 97 | + "level": "ERROR", |
| 98 | + "formatter": "json", |
| 99 | + "filename": str(LOG_DIR / "error.log"), |
| 100 | + "maxBytes": 10485760, # 10MB |
| 101 | + "backupCount": 5, |
| 102 | + "encoding": "utf-8", |
| 103 | + }, |
| 104 | + }, |
| 105 | + "loggers": { |
| 106 | + # Root logger |
| 107 | + "": { |
| 108 | + "level": "INFO", |
| 109 | + "handlers": ["console", "file", "error_file"], |
| 110 | + }, |
| 111 | + # App logger |
| 112 | + "app": { |
| 113 | + "level": "DEBUG", |
| 114 | + "handlers": ["console_json", "file", "error_file"], |
| 115 | + "propagate": False, |
| 116 | + }, |
| 117 | + # Uvicorn loggers |
| 118 | + "uvicorn": { |
| 119 | + "level": "INFO", |
| 120 | + "handlers": ["console"], |
| 121 | + "propagate": False, |
| 122 | + }, |
| 123 | + "uvicorn.access": { |
| 124 | + "level": "INFO", |
| 125 | + "handlers": ["file"], |
| 126 | + "propagate": False, |
| 127 | + }, |
| 128 | + "uvicorn.error": { |
| 129 | + "level": "INFO", |
| 130 | + "handlers": ["console", "error_file"], |
| 131 | + "propagate": False, |
| 132 | + }, |
| 133 | + # Silence watchfiles (used by uvicorn --reload) |
| 134 | + "watchfiles": { |
| 135 | + "level": "WARNING", |
| 136 | + "handlers": ["console"], |
| 137 | + "propagate": False, |
| 138 | + }, |
| 139 | + "watchfiles.main": { |
| 140 | + "level": "WARNING", |
| 141 | + "handlers": ["console"], |
| 142 | + "propagate": False, |
| 143 | + }, |
| 144 | + }, |
| 145 | +} |
| 146 | + |
| 147 | + |
| 148 | +def setup_logging(log_level: str = "INFO", use_json: bool = False) -> None: |
| 149 | + """Configure logging for the application. |
| 150 | +
|
| 151 | + Args: |
| 152 | + log_level: The minimum log level to capture (DEBUG, INFO, WARNING, ERROR, CRITICAL). |
| 153 | + use_json: Whether to use JSON formatting for console output. |
| 154 | + """ |
| 155 | + LOGGING_CONFIG["loggers"][""]["level"] = log_level |
| 156 | + LOGGING_CONFIG["loggers"]["app"]["level"] = log_level |
| 157 | + if use_json: |
| 158 | + LOGGING_CONFIG["loggers"][""]["handlers"] = [ |
| 159 | + "console_json", |
| 160 | + "file", |
| 161 | + "error_file", |
| 162 | + ] |
| 163 | + else: |
| 164 | + LOGGING_CONFIG["loggers"][""]["handlers"] = ["console", "file", "error_file"] |
| 165 | + logging.config.dictConfig(config=LOGGING_CONFIG) |
| 166 | + |
| 167 | + |
| 168 | +def get_logger(name: str) -> logging.Logger: |
| 169 | + """Get a logger instance with the specified name. |
| 170 | +
|
| 171 | + Args: |
| 172 | + name: The name of the logger (typically __name__ of the module). |
| 173 | +
|
| 174 | + Returns: |
| 175 | + A configured logger instance. |
| 176 | + """ |
| 177 | + return logging.getLogger(name=name) |
0 commit comments