I have a LOG_SETTINGS dict that looks like:
LOG_SETTINGS = {
'version': 1,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'level': 'INFO',
'formatter': 'detailed',
'stream': 'ext://sys.stdout',
},
'file': {
'class': 'logging.handlers.RotatingFileHandler',
'level': 'INFO',
'formatter': 'detailed',
'filename': '/tmp/junk.log',
'mode': 'a',
'maxBytes': 10485760,
'backupCount': 5,
},
},
'formatters': {
'detailed': {
'format': '%(asctime)s %(module)-17s line:%(lineno)-4d ' \
'%(levelname)-8s %(message)s',
},
'email': {
'format': 'Timestamp: %(asctime)s\nModule: %(module)s\n' \
'Line: %(lineno)d\nMessage: %(message)s',
},
},
'loggers': {
'extensive': {
'level':'DEBUG',
'handlers': ['file',]
},
}
}
In my code I do the following:
logging.config.dictConfig(LOG_SETTINGS)
logger = logging.getLogger('extensive')
logger.info("This is from Runner {0}".format(self.default_name))
logger2 = logging.getLogger('extensive')
logfile = logging.FileHandler("test.log")
logger2.addHandler(logfile)
logger2.info("This is from Runner {0} to the new file.".format(self.default_name))
But the output is still written to the original log file defined in LOG_SETTINGS. What I am looking for is to have the ability to say: logger2.replaceHandler(logfile) rather than addHandler.
Is there a way to do this?
If you want to send configurations to the listener which don't disable existing loggers, you will need to use a JSON format for the configuration, which will use dictConfig() for configuration. This method allows you to specify disable_existing_loggers as False in the configuration you send.
Logging LevelsWhen you set a logging level in Python using the standard module, you're telling the library you want to handle all events from that level on up. If you set the log level to INFO, it will include INFO, WARNING, ERROR, and CRITICAL messages. NOTSET and DEBUG messages will not be included here.
firstly, empty your logger handlers logger.handlers = []
then add another handler.
logger2 = logging.getLogger('extensive')
logfile = logging.FileHandler("test.log")
logger2.handlers = []
logger2.addHandler(logfile)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With