Skip to content

Commit cd761f2

Browse files
author
Jose Alonso Solis Lemus
committed
pycemrg-logs
1 parent 34ed7fa commit cd761f2

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

src/pycemrg/core/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# src/pycemrg/core/__init__.py
2+
3+
from .logs import setup_logging
4+
5+
__all__ = ["setup_logging"]

src/pycemrg/core/logs.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# src/pycemrg/core/logs.py
2+
3+
import logging
4+
from pathlib import Path
5+
from typing import Optional
6+
7+
8+
def setup_logging(
9+
log_level: int = logging.INFO, log_file: Optional[Path] = None
10+
) -> None:
11+
"""
12+
Configures the root logger for the entire project.
13+
14+
This function sets up a handler for console output and, optionally,
15+
a handler for logging to a file. It clears any existing handlers
16+
to prevent duplicate messages.
17+
"""
18+
root_logger = logging.getLogger()
19+
root_logger.setLevel(log_level)
20+
21+
for handler in root_logger.handlers[:]:
22+
root_logger.removeHandler(handler)
23+
24+
# Console Handler (always on)
25+
console_formatter = logging.Formatter("[%(name)s] %(message)s")
26+
console_handler = logging.StreamHandler()
27+
console_handler.setFormatter(console_formatter)
28+
console_handler.setLevel(log_level)
29+
root_logger.addHandler(console_handler)
30+
31+
# File Handler (optional)
32+
if log_file:
33+
log_file.parent.mkdir(parents=True, exist_ok=True)
34+
file_formatter = logging.Formatter(
35+
"[%(asctime)s] [%(levelname)s] [%(module)s:%(funcName)s] %(message)s",
36+
datefmt="%Y-%m-%d %H:%M:%S",
37+
)
38+
file_handler = logging.FileHandler(log_file)
39+
file_handler.setFormatter(file_formatter)
40+
file_handler.setLevel(logging.DEBUG) # Log more detail to the file
41+
root_logger.addHandler(file_handler)

0 commit comments

Comments
 (0)