File size: 1,968 Bytes
b13eb29
5487a42
b13eb29
5487a42
b13eb29
 
 
 
 
5487a42
b13eb29
 
5487a42
39bcecc
 
5487a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39bcecc
 
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
import logging
import time

# Define a new logging level
IMPORTANT_LEVEL_NUM = 25
logging.addLevelName(IMPORTANT_LEVEL_NUM, "IMPORTANT")

def important(self, message, *args, **kws):
    if self.isEnabledFor(IMPORTANT_LEVEL_NUM):
        # Use _log directly with the custom level
        self._log(IMPORTANT_LEVEL_NUM, message, args, **kws)

# Patch the Logger class with the new method
logging.Logger.important = important

class CustomFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        # Custom time format: Human-readable + Unix time with milliseconds
        local_time = time.strftime('%b-%d %I:%M:%S %p', time.localtime(record.created))
        unix_time_with_milliseconds = f"{record.created:.3f}"
        return f"{local_time} ({unix_time_with_milliseconds})"

    # Initializing with a format that includes the logger name, level, and message
    def __init__(self, fmt="%(asctime)s - %(name)s - %(levelname)s - %(message)s"):
        super().__init__(fmt)

def configure_logging():
    # Configure the root logger
    root_logger = logging.getLogger()
    root_logger.setLevel(IMPORTANT_LEVEL_NUM)  # Only log IMPORTANT and above

    # Clear existing handlers (if re-running this configuration in notebooks, etc.)
    root_logger.handlers = []

    # Create and set the formatter
    formatter = CustomFormatter()

    # Create a console handler using the formatter
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    console_handler.setLevel(IMPORTANT_LEVEL_NUM)

    # Add the console handler to the root logger
    root_logger.addHandler(console_handler)

    # Disable propagation for all loggers created with getLogger()
    root_logger.propagate = False

# Call the function to configure logging
configure_logging()

# Example usage
logger = logging.getLogger(__name__)
logger.important("This is an important message.")
logger.info("This info message should not appear.")