-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogging_utils.py
More file actions
89 lines (68 loc) · 2.46 KB
/
Copy pathlogging_utils.py
File metadata and controls
89 lines (68 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python3
"""Logging central do pipeline MGI.
Objetivo: um único ponto de configuração para todo o pipeline, no lugar de
`print()` espalhado. Mantém o comportamento atual no console (texto puro em
stdout, sem prefixo) e adiciona um arquivo de log estruturado e rotacionado.
Uso:
from logging_utils import get_logger
log = get_logger(__name__)
log.info("mensagem")
Nível controlado por MGI_LOG_LEVEL (default INFO).
"""
from __future__ import annotations
import logging
import os
import sys
from logging.handlers import RotatingFileHandler
from pathlib import Path
try:
import config as _config
except ImportError: # pragma: no cover - config sempre presente em runtime
_config = None
_CONFIGURED = False
def _logs_dir() -> Path:
if _config is not None and hasattr(_config, "LOGS_DIR"):
return Path(_config.LOGS_DIR)
return Path(os.environ.get("MGI_LOGS_DIR", "logs"))
def _level() -> int:
name = os.environ.get("MGI_LOG_LEVEL", "INFO").upper()
return getattr(logging, name, logging.INFO)
def configure_logging(*, force: bool = False) -> None:
"""Configura o root logger uma única vez (idempotente).
- Console: texto puro em stdout (preserva a aparência dos prints atuais).
- Arquivo: `logs/pipeline.log` rotacionado, com timestamp/nível/módulo.
"""
global _CONFIGURED
if _CONFIGURED and not force:
return
level = _level()
root = logging.getLogger()
root.setLevel(level)
for handler in list(root.handlers):
root.removeHandler(handler)
console = logging.StreamHandler(sys.stdout)
console.setLevel(level)
console.setFormatter(logging.Formatter("%(message)s"))
root.addHandler(console)
try:
logs_dir = _logs_dir()
logs_dir.mkdir(parents=True, exist_ok=True)
file_handler = RotatingFileHandler(
logs_dir / "pipeline.log",
maxBytes=2_000_000,
backupCount=5,
encoding="utf-8",
)
file_handler.setLevel(level)
file_handler.setFormatter(
logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
)
root.addHandler(file_handler)
except OSError:
# Sem permissão/erro de disco: segue apenas com console.
pass
_CONFIGURED = True
def get_logger(name: str) -> logging.Logger:
"""Retorna um logger garantindo que o logging esteja configurado."""
configure_logging()
return logging.getLogger(name)