Files
sld-filebackups-py/logger.py

50 lines
1.5 KiB
Python

# logger.py
import logging
import json
from pathlib import Path
import os
def _load_config():
cfg_path = Path(__file__).parent / "config.json"
if cfg_path.exists():
try:
return json.loads(cfg_path.read_text())
except Exception:
return {}
return {}
def setup_logger():
cfg = _load_config()
logs_enabled = bool(cfg.get("logs", False))
logs_path = cfg.get("logs_path", None)
root_logger = logging.getLogger()
# reset handlers (utile se viene richiamato più volte)
root_logger.handlers = []
formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
# always add a stream handler so messages appear on console (useful for cron output)
sh = logging.StreamHandler()
sh.setFormatter(formatter)
sh.setLevel(logging.INFO)
root_logger.addHandler(sh)
if logs_enabled:
if logs_path is None:
# default fallback
logs_path = str(Path.home() / "backups" / "logs")
log_dir = Path(logs_path)
log_dir.mkdir(parents=True, exist_ok=True)
fh = logging.FileHandler(log_dir / "backup.log")
fh.setFormatter(formatter)
fh.setLevel(logging.INFO)
root_logger.addHandler(fh)
root_logger.setLevel(logging.INFO)
# informative note when file logging is disabled
if not logs_enabled:
root_logger.info("File logging disabled (config.json: logs=false)")
else:
root_logger.info(f"File logging enabled, log file: {logs_path}/backup.log")