-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_util.py
44 lines (35 loc) · 1.41 KB
/
log_util.py
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
"""
log_util.py: Provides centralized logging across the application.
Enhanced to support both console and optional file logging, facilitating easier
identification of message sources and maintaining consistent logging practices.
"""
import logging
def app_logger(name, level=logging.INFO, log_file=None):
"""
Configures a logger with a specified name, format, and log level.
Optionally supports logging to a file.
:param name: Logger name, typically __name__ from the importing module.
:param level: Logging level, defaults to logging.INFO.
:param log_file: Optional. If provided, logs will also be written to this file.
:return: Configured logger instance.
"""
# Create a logger
logger = logging.getLogger(name)
logger.setLevel(level)
logger.handlers.clear() # Clear existing handlers to avoid duplicates
# Create formatter
formatter = logging.Formatter(
fmt="%(asctime)s - %(levelname)s - %(module)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
# Console handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# File handler (if log_file is specified)
if log_file:
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(level)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger