-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.py
More file actions
70 lines (58 loc) · 1.81 KB
/
logger.py
File metadata and controls
70 lines (58 loc) · 1.81 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
# logger.py
import logging
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
# Use a single canonical name everywhere
_LOGGER_NAME = "AskMe-FAQ-Bot"
_INITIALIZED = False
def setup_logging() -> logging.Logger:
"""
Configure application logging (idempotent).
Handlers:
- Console (INFO)
- Daily rotating file: logs/daily.log (rotates at midnight, keeps 14)
- Aggregate file: logs/app.log (append)
Returns
-------
logging.Logger
The configured 'AskMe-FAQ-Bot' logger.
"""
global _INITIALIZED
logger = logging.getLogger(_LOGGER_NAME)
if _INITIALIZED or logger.handlers:
return logger
logger.setLevel(logging.INFO)
logger.propagate = False
log_dir = Path("logs")
log_dir.mkdir(parents=True, exist_ok=True)
fmt = logging.Formatter(
"%(asctime)s | %(levelname)s | %(name)s:%(lineno)d - %(message)s",
"%Y-%m-%d %H:%M:%S",
)
# Console
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(fmt)
logger.addHandler(ch)
# Daily rotating file
rh = TimedRotatingFileHandler(
log_dir / "daily.log",
when="midnight",
interval=1,
backupCount=14,
encoding="utf-8"
)
rh.setLevel(logging.INFO)
rh.setFormatter(fmt)
logger.addHandler(rh)
# Aggregate file
fh = logging.FileHandler(log_dir / "app.log", encoding="utf-8", mode="a")
fh.setLevel(logging.INFO)
fh.setFormatter(fmt)
logger.addHandler(fh)
_INITIALIZED = True
logger.info("Logging initialized. Daily: %s | Aggregate: %s", log_dir / "daily.log", log_dir / "app.log")
return logger
def get_logger() -> logging.Logger:
"""Return the configured logger without reconfiguring handlers."""
return logging.getLogger(_LOGGER_NAME)