2323 / shared /utils /logging.py
GreenMan101
Add Doctor Freud Bot - all files
55b6d21
Raw History Blame Contribute Delete
2.09 kB
"""Structured logging utilities."""
import logging
import json
import sys
from datetime import datetime
from typing import Any, Dict
class JSONFormatter(logging.Formatter):
"""Custom formatter that outputs logs in JSON format."""
def format(self, record: logging.LogRecord) -> str:
log_data: Dict[str, Any] = {
"timestamp": datetime.utcnow().isoformat() + "Z",
"level": record.levelname,
"service": record.name,
"message": record.getMessage(),
}
# Add extra fields if present
if hasattr(record, "chat_id"):
log_data["chat_id"] = record.chat_id
if hasattr(record, "user_id"):
log_data["user_id"] = record.user_id
if hasattr(record, "message_id"):
log_data["message_id"] = record.message_id
if hasattr(record, "latency_ms"):
log_data["latency_ms"] = record.latency_ms
if hasattr(record, "trace_id"):
log_data["trace_id"] = record.trace_id
# Add exception info if present
if record.exc_info:
log_data["exception"] = self.formatException(record.exc_info)
return json.dumps(log_data)
def setup_logging(service_name: str, log_level: str = "INFO") -> logging.Logger:
"""
Set up structured logging for a service.
Args:
service_name: Name of the service (e.g., "core-service")
log_level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
Returns:
Configured logger instance
"""
logger = logging.getLogger(service_name)
logger.setLevel(getattr(logging, log_level.upper()))
# Remove existing handlers
logger.handlers.clear()
# Console handler with JSON formatting
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(JSONFormatter())
logger.addHandler(console_handler)
return logger
def get_logger(name: str) -> logging.Logger:
"""Get a logger instance."""
return logging.getLogger(name)