|
| 1 | +""" |
| 2 | +Logging utilities for CiberWebScan. |
| 3 | +
|
| 4 | +Provides centralized logging configuration. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import logging |
| 10 | +import logging.config |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +from ciberwebscan.config.models import LoggingConfig |
| 14 | + |
| 15 | + |
| 16 | +def setup_logging(config: LoggingConfig) -> None: |
| 17 | + """ |
| 18 | + Configure logging based on the provided configuration. |
| 19 | +
|
| 20 | + Args: |
| 21 | + config: Logging configuration from app config. |
| 22 | + """ |
| 23 | + # Convert level string to logging level |
| 24 | + level_map = { |
| 25 | + "DEBUG": logging.DEBUG, |
| 26 | + "INFO": logging.INFO, |
| 27 | + "WARNING": logging.WARNING, |
| 28 | + "ERROR": logging.ERROR, |
| 29 | + "CRITICAL": logging.CRITICAL, |
| 30 | + } |
| 31 | + level = level_map.get(config.level.upper(), logging.INFO) |
| 32 | + |
| 33 | + # Base logging configuration |
| 34 | + logging_config = { |
| 35 | + "version": 1, |
| 36 | + "disable_existing_loggers": False, |
| 37 | + "formatters": { |
| 38 | + "default": { |
| 39 | + "format": config.format, |
| 40 | + }, |
| 41 | + }, |
| 42 | + "handlers": { |
| 43 | + "console": { |
| 44 | + "class": "logging.StreamHandler", |
| 45 | + "formatter": "default", |
| 46 | + "level": level, |
| 47 | + }, |
| 48 | + }, |
| 49 | + "root": { |
| 50 | + "level": level, |
| 51 | + "handlers": ["console"], |
| 52 | + }, |
| 53 | + } |
| 54 | + |
| 55 | + # Add file handler if file is specified |
| 56 | + if config.file: |
| 57 | + file_path = Path(config.file) |
| 58 | + file_path.parent.mkdir(parents=True, exist_ok=True) |
| 59 | + |
| 60 | + logging_config["handlers"]["file"] = { |
| 61 | + "class": "logging.handlers.RotatingFileHandler", |
| 62 | + "formatter": "default", |
| 63 | + "filename": str(file_path), |
| 64 | + "maxBytes": config.max_size, |
| 65 | + "backupCount": config.backup_count, |
| 66 | + "level": level, |
| 67 | + } |
| 68 | + logging_config["root"]["handlers"].append("file") |
| 69 | + |
| 70 | + # Apply configuration |
| 71 | + logging.config.dictConfig(logging_config) |
0 commit comments