Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging in Python with Config File - Using handlers defined in file through code

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?

like image 503
RedBaron Avatar asked Dec 07 '10 10:12

RedBaron


2 Answers

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)
like image 138
Iacks Avatar answered Oct 03 '22 05:10

Iacks


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.

like image 31
martineau Avatar answered Oct 03 '22 03:10

martineau