Biz / logging_config.py
pranav8tripathi@gmail.com
init
134d9db
"""Logging configuration for RivalLens."""
import logging
import sys
import os
from pathlib import Path
def configure_logging():
"""Configure logging for the application."""
import logging.config
# Create logs directory if it doesn't exist
log_dir = Path("/app/logs")
log_dir.mkdir(exist_ok=True)
# Ensure the log file is writable
log_file = log_dir / "rival_lens.log"
try:
log_file.touch(mode=0o666, exist_ok=True)
except PermissionError:
# If we can't write to the file, fall back to console only
log_file = None
# Logging configuration
LOGGING_CONFIG = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S"
},
},
"handlers": {
"console": {
"level": "INFO",
"formatter": "standard",
"class": "logging.StreamHandler",
"stream": sys.stdout,
},
},
"loggers": {
"": { # root logger
"handlers": ["console"],
"level": "INFO",
"propagate": True
},
"app": {
"handlers": ["console"],
"level": "INFO",
"propagate": False
},
"__main__": {
"handlers": ["console"],
"level": "INFO",
"propagate": False
},
}
}
# Only add file handler if we can write to the log file
if log_file and os.access(log_file, os.W_OK):
LOGGING_CONFIG["handlers"]["file"] = {
"level": "DEBUG",
"formatter": "standard",
"class": "logging.handlers.RotatingFileHandler",
"filename": str(log_file),
"maxBytes": 10485760, # 10MB
"backupCount": 5,
"encoding": "utf8"
}
# Add file handler to all loggers
for logger in LOGGING_CONFIG["loggers"].values():
if "handlers" in logger:
logger["handlers"].append("file")
# Apply the configuration
logging.config.dictConfig(LOGGING_CONFIG)
# Get logger for this module
logger = logging.getLogger(__name__)
logger.info("Logging configured")
# Log where logs are being written to
if log_file and os.access(log_file, os.W_OK):
logger.info(f"Logging to file: {log_file}")
else:
logger.warning("File logging is disabled. Logging to console only.")
return logger