second-space / custom_logging.py
Mehul Patel
improved logging
5487a42
Raw
History Blame Contribute Delete
1.97 kB
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.")