58 lines
1.4 KiB
Python
58 lines
1.4 KiB
Python
#!/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,
|
|
)
|