I am using logging module of python. How can I access the handlers defined in config file from the code. As an example, I have a logger defined and two handlers - one for screen and other for file. I want to use appropriate handler based on user preference (whether they want to log on screen or to a file). How can I dynamically add and remove handlers defined in config file from loggers defined in config file?
[loggers]
keys=root,netmap
[handlers]
keys=fil,screen
[logger_root]
level=NOTSET
handlers=
[logger_netmap]
level=INFO
handlers=fil,screen
qualname=netmap
[formatters]
keys = simple
[formatter_simple]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
[handler_fil]
class=handlers.RotatingFileHandler
args=('file.log','a','maxBytes=10000','backupCount=5')
formatter=simple
[handler_screen]
class=StreamHandler
args = (sys.stdout,)
formatter=simple
Depending on whether user runs the program with -v or not I need to use one of File or Screen Handler. How can I add or delete fil or screen handlers from netmap logger?
Instead of having to dynamically change the config file, just use Logger.addHandler(handler).
fileHandler = logging.handlers.RotatingFileHandler('file.log', mode='a', maxBytes=10000, backupCount=5)
logger = logging.getLogger('netmap')
if LOG_TO_FILE:
logger.addHandler(fileHandler)
Then to load in formatting from perhaps the same file;
import ConfigParser
configParser = ConfigParser.ConfigParser()
config.read('config.ini')
format = config.get('formatter_simple', 'format')
fileHandler.setFormatter(format)
From the logging
module's documentation it looks like logging
objects have these two methods:
Logger.addHandler(hdlr)
Adds the specified handler hdlr to this logger.
Logger.removeHandler(hdlr)
Removes the specified handler hdlr from this logger.
So it seems like you ought be able to use them to add or change the netmap logger handler to be whatever you want based on what's in the config file.
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