开发者

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

开发者 https://www.devze.com 2023-01-29 01:12 出处:网络
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

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.RotatingF开发者_Go百科ileHandler
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.


Ok So I found an elegant way through a gud soul on the python google group. It works like charm. Here's the code

import logging
import getopt
import sys
import logging.config

def stop(m,handl):
    consoleHand=[h for h in m.handlers if h.__class__ is handl]
    print consoleHand
    if consoleHand:
        h1=consoleHand[0]
        h1.filter=lambda x: False


logging.config.fileConfig('log.conf')
my_log = logging.getLogger('netmap')
args=sys.argv[1:]
opt,arg = getopt.gnu_getopt(args,'v')
l=''
for o,a in opt:
    if o=='-v':
        l='verbose'
        stop(my_log,logging.handlers.RotatingFileHandler)
if not l:
    stop(my_log,logging.StreamHandler)
my_log.debug('Starting.....')
my_log.warning('Unstable')
my_log.error('FIles Missing')
my_log.critical('BlowOut!!')

The config file is still the same. I can now easily activate or deactivate handlers.

0

精彩评论

暂无评论...
验证码 换一张
取 消