I am stuck at situation where i have to
emit logs in different format based on condition like security events, normal software operation events etc to the std out.
example
lets say
- security events like authentication failure/success should start
like SEC EVENT,LEVEL, DATETIME, MESSAGE - normal events should start
like LEVEL, DATETIME, MESSAGE
I tried using formatter and Filters but all these make decision at the time when my custom logger class is initialized, I need to make that decision during execution time
example:
log = CustomLogClass()
log.info("msg") # this should emit in some format
log.sec_info() # this should emit in other format
2
what is suggested in the comments will be something similar to this:
class CustomLogClass:
def __init__(self):
self.normal_logger = self._create_logger('normal_logger',
'%(levelname)s, %(asctime)s, %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
self.sec_logger = self._create_logger('sec_logger'),
'%(levelname)s, %(asctime)s, %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
def _create_logger(self, name, log_format, level=logging.INFO):
# Create a new logger with the specified name
logger = logging.getLogger(name)
logger.setLevel(level)
handler = logging.StreamHandler()
formatter = logging.Formatter(log_format, datefmt='%Y-%m-%d %H:%M:%S')
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
def info(self, message):
"""Logs a normal event."""
self.normal_logger.info(message)
def sec_info(self, message):
"""Logs a security event."""
self.sec_logger.info(message)
This is what I meant in my comment:
import logging
class CustomLogClass:
logger1 = logging.getLogger('logger1')
logger1.setLevel(logging.INFO)
formatter1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler1 = logging.StreamHandler()
console_handler1.setFormatter(formatter1)
logger1.addHandler(console_handler1)
# Configure the second logger with a different format
logger2 = logging.getLogger('logger2')
logger2.setLevel(logging.DEBUG)
formatter2 = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler2 = logging.StreamHandler()
console_handler2.setFormatter(formatter2)
logger2.addHandler(console_handler2)
def log_situation1(self, message):
self.logger1.info(message)
def log_situation2(self, message):
self.logger2.info(message)
custom_logger = CustomLogClass()
is_situation1 = True
if is_situation1:
custom_logger.log_situation1("situation 1 happened")
else:
custom_logger.log_situation2("situation 2 happened")