|
import logging |
|
import sys |
|
from pathlib import Path |
|
from typing import Optional |
|
|
|
def setup_logger( |
|
name: str, |
|
log_dir: Optional[Path] = None, |
|
debug: bool = False |
|
) -> logging.Logger: |
|
"""Sets up a standardized logger for the toolkit. |
|
|
|
Args: |
|
name: Name of the logger/module |
|
log_dir: Directory to store log files. If None, only console logging is enabled |
|
debug: Whether to enable debug logging |
|
|
|
Returns: |
|
Configured logger instance |
|
""" |
|
logger = logging.getLogger(name) |
|
logger.setLevel(logging.DEBUG if debug else logging.INFO) |
|
|
|
|
|
logger.handlers.clear() |
|
|
|
|
|
ch = logging.StreamHandler(sys.stdout) |
|
ch.setLevel(logging.DEBUG if debug else logging.INFO) |
|
ch_formatter = logging.Formatter('%(levelname)s - %(message)s') |
|
ch.setFormatter(ch_formatter) |
|
logger.addHandler(ch) |
|
|
|
|
|
if log_dir: |
|
log_dir = Path(log_dir) |
|
log_dir.mkdir(parents=True, exist_ok=True) |
|
|
|
fh = logging.FileHandler(log_dir / f"{name}.log") |
|
fh.setLevel(logging.DEBUG) |
|
fh_formatter = logging.Formatter( |
|
'%(asctime)s - %(name)s - %(levelname)s - %(message)s' |
|
) |
|
fh.setFormatter(fh_formatter) |
|
logger.addHandler(fh) |
|
|
|
return logger |
|
|