File size: 2,582 Bytes
a8949a8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
#!/usr/bin/env python
import os
import logging
from pathlib import Path
def setup_logging(
logger_name,
log_level=logging.INFO,
console=True,
log_filename=None
):
"""
Configure logging for a module or application.
This function provides a flexible logging setup that automatically
manages log file creation and configuration.
Args:
logger_name (str): Name of the logger. Used to generate log filename
if no specific filename is provided.
log_level (int, optional): Logging level.
Defaults to logging.INFO.
Can use standard logging levels like:
- logging.DEBUG
- logging.INFO
- logging.WARNING
- logging.ERROR
- logging.CRITICAL
console (bool, optional): Whether to enable console logging.
Defaults to True.
log_filename (str or Path, optional): Custom log filename.
If None, uses logger_name to generate filename.
Returns:
logging.Logger: Configured logger instance with file and/or console handlers.
"""
# Fixed log directory path
log_dir = Path("./data/logs")
log_dir.mkdir(parents=True, exist_ok=True) # Ensure directory exists
# Create logger
logger = logging.getLogger(logger_name)
logger.setLevel(log_level)
# Clear any existing handlers to prevent duplicate logging
if logger.handlers:
logger.handlers.clear()
# Create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# Determine log file path
if log_filename:
# If a full path is provided, extract just the filename
log_filename = Path(log_filename)
log_file = log_dir / log_filename.name
else:
# Use logger name to create log filename
log_file = log_dir / f"{logger_name.lower()}.log"
# Create file handler
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
# Add console handler if requested
if console:
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# Print configuration details
print(f"Logging configuration:")
print(f" Logger name: {logger_name}")
print(f" Log level: {logging.getLevelName(log_level)}")
print(f" Log file: {log_file}")
logger.info(f"Logging configured for {logger_name}")
return logger |