feat: add logging config
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
54
src/logging_config.py
Normal file
54
src/logging_config.py
Normal file
@@ -0,0 +1,54 @@
|
||||
"""Logging configuration for ai-chat-exporter."""
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def setup_logging(
|
||||
level: int = logging.INFO,
|
||||
log_file: str | None = None,
|
||||
no_log_file: bool = False,
|
||||
) -> None:
|
||||
"""Configure console and rotating file logging.
|
||||
|
||||
Args:
|
||||
level: Console log level (e.g. logging.DEBUG, logging.INFO).
|
||||
log_file: Path to the log file. None uses the default location.
|
||||
Set to "none" (string) to disable file logging.
|
||||
no_log_file: If True, disables file logging entirely.
|
||||
"""
|
||||
fmt = "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s"
|
||||
datefmt = "%Y-%m-%d %H:%M:%S"
|
||||
formatter = logging.Formatter(fmt, datefmt=datefmt)
|
||||
|
||||
root = logging.getLogger()
|
||||
root.setLevel(logging.DEBUG) # root catches everything; handlers filter
|
||||
|
||||
# Remove any existing handlers (idempotent for test environments)
|
||||
root.handlers.clear()
|
||||
|
||||
# Console handler
|
||||
console = logging.StreamHandler()
|
||||
console.setLevel(level)
|
||||
console.setFormatter(formatter)
|
||||
root.addHandler(console)
|
||||
|
||||
# File handler
|
||||
if not no_log_file and log_file and log_file.lower() != "none":
|
||||
log_path = Path(log_file).expanduser()
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_path,
|
||||
maxBytes=5 * 1024 * 1024, # 5 MB
|
||||
backupCount=3,
|
||||
encoding="utf-8",
|
||||
)
|
||||
file_handler.setLevel(logging.DEBUG) # always DEBUG to file
|
||||
file_handler.setFormatter(formatter)
|
||||
root.addHandler(file_handler)
|
||||
|
||||
# Suppress noisy third-party loggers
|
||||
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
||||
logging.getLogger("requests").setLevel(logging.WARNING)
|
||||
Reference in New Issue
Block a user