add logging config, related to #8

This commit is contained in:
2026-05-29 09:43:28 +02:00
parent 00a99a8d2c
commit d1136178de

View File

@@ -1,5 +1,6 @@
from __future__ import annotations
import dataclasses as dc
import logging
import logging.handlers
from pathlib import Path
@@ -21,33 +22,41 @@ NULL_HANDLER = logging.NullHandler()
BASE_LOGGER = logging.getLogger("dopt_base")
@dc.dataclass(eq=False, slots=True, kw_only=True)
class LoggingConfig:
enable_stderr: bool
enable_file: bool = False
logging_dir: Path | None = None
log_filename: str = LOG_FILENAME
file_max_bytes: int = 5_242_880
file_backup_count: int = 1
def setup_logging(
enable_stderr: bool,
enable_file: bool = False,
logging_dir: Path | None = None,
log_filename: str = LOG_FILENAME,
config: LoggingConfig,
) -> None:
# ** formatters
logging.Formatter.converter = gmtime
LOGGER_ALL_FORMATER = logging.Formatter(fmt=LOG_FMT, datefmt=LOG_DATE_FMT)
# ** handlers
if enable_stderr:
if config.enable_stderr:
logger_all_handler_stderr = logging.StreamHandler()
logger_all_handler_stderr.setLevel(DEFAULT_LOGLEVEL_STDERR)
logger_all_handler_stderr.setFormatter(LOGGER_ALL_FORMATER)
else: # pragma: no cover
logger_all_handler_stderr = NULL_HANDLER
if enable_file and logging_dir is None:
if config.enable_file and config.logging_dir is None:
raise ValueError("Logging path must be provided to write to log file")
elif enable_file:
assert logging_dir
log_file_path = logging_dir / log_filename
elif config.enable_file:
if config.logging_dir is None:
raise ValueError("Logging directory must be provided if file writing is selected")
log_file_path = config.logging_dir / config.log_filename
logger_all_handler_file = logging.handlers.RotatingFileHandler(
log_file_path,
encoding="utf-8",
maxBytes=5_242_880,
backupCount=1,
maxBytes=config.file_max_bytes,
backupCount=config.file_backup_count,
delay=True,
)
logger_all_handler_file.setLevel(DEFAULT_LOGLEVEL_FILE)