From 720c2fd910fe91b95f0daaed7d69393c28b00c52 Mon Sep 17 00:00:00 2001 From: admin Date: Mon, 18 May 2026 15:13:31 +0000 Subject: [PATCH] feat: add utils (config loader, logging setup) --- ns8_backup_monitor/utils.py | 57 +++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 ns8_backup_monitor/utils.py diff --git a/ns8_backup_monitor/utils.py b/ns8_backup_monitor/utils.py new file mode 100644 index 0000000..c182571 --- /dev/null +++ b/ns8_backup_monitor/utils.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 +""" +utils.py - Shared utilities: config loading, logging setup. +""" + +import logging +import logging.handlers +import sys +from pathlib import Path + +try: + import yaml +except ImportError: + yaml = None + + +DEFAULT_CONFIG_PATHS = [ + "/etc/ns8-backup-monitor/config.yml", + "/opt/ns8-backup-monitor/config/config.yml", + "config/config.yml", +] + + +def load_config(path: str = None) -> dict: + if yaml is None: + raise ImportError("PyYAML not installed. Run: pip3 install pyyaml") + + paths = [path] if path else DEFAULT_CONFIG_PATHS + for p in paths: + if p and Path(p).exists(): + with open(p) as f: + return yaml.safe_load(f) or {} + + raise FileNotFoundError( + f"No config file found. Tried: {paths}\n" + "Copy config/config.yml.example to config/config.yml and edit it." + ) + + +def setup_logging(config: dict): + log_cfg = config.get("logging", {}) + level = getattr(logging, log_cfg.get("level", "INFO").upper(), logging.INFO) + log_file = log_cfg.get("file", "") + + handlers = [logging.StreamHandler(sys.stdout)] + if log_file: + handlers.append( + logging.handlers.RotatingFileHandler( + log_file, maxBytes=5 * 1024 * 1024, backupCount=3 + ) + ) + + logging.basicConfig( + level=level, + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", + handlers=handlers, + )