Spaces:
Running
Running
Download src/logging_config.py from reputeradar/ioc-core: direct link, hf CLI and curl.
- Browser
- Download file 7.45 kB
-
https://huggingface.co/spaces/reputeradar/ioc-core/resolve/main/src/logging_config.py
- Command line
-
hf download hf://spaces/reputeradar/ioc-core/src/logging_config.py
-
curl -L -o logging_config.py https://huggingface.co/spaces/reputeradar/ioc-core/resolve/main/src/logging_config.py
7.45 kB
| """Enhanced logging configuration for the application.""" | |
| import logging | |
| import sys | |
| import time | |
| import uuid | |
| from contextvars import ContextVar | |
| from src.config import settings | |
| # Context variable for request ID tracking | |
| request_id_var: ContextVar[str] = ContextVar("request_id", default="-") | |
| class RequestIdFilter(logging.Filter): | |
| """Add request ID to log records for request tracing.""" | |
| def filter(self, record: logging.LogRecord) -> bool: | |
| record.request_id = request_id_var.get("-") | |
| return True | |
| class DetailedFormatter(logging.Formatter): | |
| """ | |
| Enhanced formatter with colors and structured output for development. | |
| Includes: timestamp, level, module, function, line number, request ID, and message. | |
| """ | |
| # ANSI color codes | |
| COLORS = { | |
| "DEBUG": "\033[36m", # Cyan | |
| "INFO": "\033[32m", # Green | |
| "WARNING": "\033[33m", # Yellow | |
| "ERROR": "\033[31m", # Red | |
| "CRITICAL": "\033[35m", # Magenta | |
| } | |
| RESET = "\033[0m" | |
| BOLD = "\033[1m" | |
| DIM = "\033[2m" | |
| def __init__(self, use_colors: bool = True): | |
| super().__init__() | |
| self.use_colors = use_colors | |
| def format(self, record: logging.LogRecord) -> str: | |
| # Get request ID (default to "-" if not set) | |
| request_id = getattr(record, "request_id", "-") | |
| # Format timestamp | |
| timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(record.created)) | |
| milliseconds = int((record.created % 1) * 1000) | |
| # Get level color | |
| level_color = self.COLORS.get(record.levelname, "") | |
| # Format location (module:function:line) | |
| location = f"{record.module}.{record.funcName}:{record.lineno}" | |
| if self.use_colors: | |
| # Colored output for terminal | |
| level_str = f"{level_color}{self.BOLD}{record.levelname:8}{self.RESET}" | |
| timestamp_str = f"{self.DIM}{timestamp}.{milliseconds:03d}{self.RESET}" | |
| location_str = f"{self.DIM}{location}{self.RESET}" | |
| request_id_str = f"[{request_id[:8]}]" if request_id != "-" else "" | |
| return f"{timestamp_str} {level_str} {location_str} {request_id_str} {record.getMessage()}" | |
| else: | |
| # Plain text for file logging | |
| request_id_str = f"[{request_id}]" if request_id != "-" else "" | |
| return f"{timestamp}.{milliseconds:03d} | {record.levelname:8} | {location:40} | {request_id_str} {record.getMessage()}" | |
| class APILogFormatter(logging.Formatter): | |
| """Structured formatter for API request/response logging.""" | |
| def format(self, record: logging.LogRecord) -> str: | |
| # Check if this is an API log with extra data | |
| if hasattr(record, "api_data"): | |
| data = record.api_data | |
| parts = [ | |
| f"[{data.get('provider', 'UNKNOWN')}]", | |
| f"{data.get('method', '')} {data.get('endpoint', '')}", | |
| ] | |
| if "status_code" in data: | |
| parts.append(f"-> {data['status_code']}") | |
| if "duration_ms" in data: | |
| parts.append(f"({data['duration_ms']:.0f}ms)") | |
| if "error" in data: | |
| parts.append(f"ERROR: {data['error']}") | |
| return " ".join(parts) | |
| return super().format(record) | |
| def get_request_id() -> str: | |
| """Get the current request ID from context.""" | |
| return request_id_var.get("-") | |
| def set_request_id(request_id: str | None = None) -> str: | |
| """ | |
| Set a request ID for the current context. | |
| Args: | |
| request_id: Optional request ID (generates UUID if not provided) | |
| Returns: | |
| The request ID that was set | |
| """ | |
| if request_id is None: | |
| request_id = str(uuid.uuid4()) | |
| request_id_var.set(request_id) | |
| return request_id | |
| def log_api_call( | |
| logger: logging.Logger, | |
| provider: str, | |
| method: str, | |
| endpoint: str, | |
| status_code: int | None = None, | |
| duration_ms: float | None = None, | |
| error: str | None = None, | |
| level: int = logging.DEBUG, | |
| ) -> None: | |
| """ | |
| Log an API call with structured data. | |
| Args: | |
| logger: Logger instance | |
| provider: API provider name (e.g., "ThreatFox", "VirusTotal") | |
| method: HTTP method | |
| endpoint: API endpoint | |
| status_code: Response status code | |
| duration_ms: Request duration in milliseconds | |
| error: Error message if request failed | |
| level: Log level | |
| """ | |
| api_data = { | |
| "provider": provider, | |
| "method": method, | |
| "endpoint": endpoint, | |
| } | |
| if status_code is not None: | |
| api_data["status_code"] = status_code | |
| if duration_ms is not None: | |
| api_data["duration_ms"] = duration_ms | |
| if error is not None: | |
| api_data["error"] = error | |
| level = logging.ERROR | |
| # Create log record with extra data | |
| record = logger.makeRecord( | |
| logger.name, | |
| level, | |
| "", | |
| 0, | |
| f"[{provider}] {method} {endpoint}" + (f" -> {status_code}" if status_code else "") + (f" ({duration_ms:.0f}ms)" if duration_ms else "") + (f" ERROR: {error}" if error else ""), | |
| (), | |
| None, | |
| ) | |
| record.api_data = api_data | |
| logger.handle(record) | |
| def setup_logging(log_level: str | None = None) -> None: | |
| """ | |
| Configure application-wide logging with enhanced detail. | |
| Args: | |
| log_level: Optional log level override (defaults to settings.LOG_LEVEL) | |
| """ | |
| log_level = log_level or settings.LOG_LEVEL | |
| # Convert string to logging level | |
| numeric_level = getattr(logging, log_level.upper(), logging.INFO) | |
| # Check if we're in a TTY (terminal) for color support | |
| use_colors = hasattr(sys.stdout, "isatty") and sys.stdout.isatty() | |
| # Create formatter | |
| formatter = DetailedFormatter(use_colors=use_colors) | |
| # Configure root logger | |
| root_logger = logging.getLogger() | |
| root_logger.setLevel(numeric_level) | |
| # Remove existing handlers | |
| for handler in root_logger.handlers[:]: | |
| root_logger.removeHandler(handler) | |
| # Console handler with detailed formatting | |
| console_handler = logging.StreamHandler(sys.stdout) | |
| console_handler.setLevel(numeric_level) | |
| console_handler.setFormatter(formatter) | |
| console_handler.addFilter(RequestIdFilter()) | |
| root_logger.addHandler(console_handler) | |
| # Set logging level for third-party libraries (reduce noise) | |
| logging.getLogger("uvicorn").setLevel(logging.INFO) | |
| logging.getLogger("uvicorn.access").setLevel(logging.WARNING) | |
| logging.getLogger("uvicorn.error").setLevel(logging.INFO) | |
| logging.getLogger("fastapi").setLevel(logging.INFO) | |
| logging.getLogger("requests").setLevel(logging.WARNING) | |
| logging.getLogger("urllib3").setLevel(logging.WARNING) | |
| logging.getLogger("httpx").setLevel(logging.WARNING) | |
| # Application loggers at debug level when in DEBUG mode | |
| if numeric_level == logging.DEBUG: | |
| logging.getLogger("src").setLevel(logging.DEBUG) | |
| logging.getLogger("src.services").setLevel(logging.DEBUG) | |
| logging.getLogger("src.api").setLevel(logging.DEBUG) | |
| logging.info(f"Logging configured: level={log_level}, colors={use_colors}") | |
| # Convenience logger creation | |
| def get_logger(name: str) -> logging.Logger: | |
| """ | |
| Get a logger with the application's configuration. | |
| Args: | |
| name: Logger name (usually __name__) | |
| Returns: | |
| Configured logger instance | |
| """ | |
| return logging.getLogger(name) | |