-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog_setup.py
74 lines (63 loc) · 2.44 KB
/
log_setup.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
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
# log_config.py
import logging
from logging import Logger
from math import exp
import coloredlogs
from tqdm import tqdm
logger = Logger("tmp")
class TqdmHandler(logging.StreamHandler):
"""
Custom logging handler utilizing tqdm for progress bar support in logging.
This handler allows log messages to be displayed over tqdm progress bars without interrupting them.
"""
def emit(self, record):
"""
Emit a log record.
Logs are emitted using tqdm.write to ensure compatibility with tqdm progress bars,
preventing them from being disrupted by log messages.
Args:
record (logging.LogRecord): The log record to be emitted.
"""
try:
# Format the log message
msg = self.format(record)
# Write the message using tqdm to avoid interfering with progress bars
tqdm.write(msg, end="")
except Exception:
# Handle any errors that occur during logging
self.handleError(record)
def setup_logging(log_level: str = "WARN"):
"""
Sets up logging with a custom handler and formatter.
This function configures the root logger to use a TqdmHandler for output, allowing log messages
to be displayed over tqdm progress bars. It also uses coloredlogs for colored log output.
Args:
log_level (str, optional): The minimum log level for messages to be handled. Defaults to "WARN".
"""
global logger
# Get the root logger
logger = logging.getLogger()
# Create an instance of the custom TqdmHandler
handler = TqdmHandler()
# Define a formatter with a specific format string, including colored output
# Updated to show the filename and line number instead of hostname
formatter = coloredlogs.ColoredFormatter(
"%(asctime)s %(filename)s:%(lineno)d %(name)s[%(process)d] %(levelname)s %(message)s"
)
# Set the formatter for the handler
handler.setFormatter(formatter)
# Add the custom handler to the logger
logger.addHandler(handler)
# Set the logger's level to the specified log level
logger.setLevel(log_level)
# Install coloredlogs with the specified log level and logger
coloredlogs.install(level=log_level, logger=logger)
def get_logger():
"""
Returns the global logger instance.
Returns:
logging.Logger: The global logger instance.
"""
if logger is None:
setup_logging()
return logger