Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logging in python

Tags:

python

i want to create separate logging file in python like info.log, debug.log, error.log i have a setting file(logging.conf) for logging as given below

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

and i have created logging.py file as given below

import logging
import logging.config

logging.config.fileConfig('logging.conf')

# create logger
logger = logging.getLogger('simpleExample')

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

but when execute logging.py file i am getting following result in consol

2012-12-10 13:30:20,030 - simpleExample - DEBUG - debug message
2012-12-10 13:30:20,031 - simpleExample - INFO - info message
2012-12-10 13:30:20,032 - simpleExample - WARNING - warn message
2012-12-10 13:30:20,032 - simpleExample - ERROR - error message
2012-12-10 13:30:20,033 - simpleExample - CRITICAL - critical message

as i have told i want to create separate file in log.info, debug.info, error.info. thanks in advance

like image 837
Satyendra Avatar asked Dec 10 '12 08:12

Satyendra


1 Answers

You need to config multiple handler to output different level log to different files. For example, you want to INFO level log to info.log, you can define a fileHandler with INFO filer

class MyFilter(logging.Filter):
    def filter(self, rec):
        return rec.levelno == logging.INFO

class MyHandler(logging.FileHandler):
    def __init__(self, *arg, **kw):
        logging.FileHandler.__init__(self, *arg, **kw)
        self.addFilter(MyFilter())

And add it to logging namespace:

logging.MyHandler = MyHandler

so you can use it in your config file:

[handlers]
keys=consoleHandler,onlyinfoHandler
[handler_onlyinfoHandler]
class=MyHandler
level=DEBUG
formatter=simpleFormatter
args=('info.log','w')

You can continue to add others or use level as handler args.

like image 178
elprup Avatar answered Sep 23 '22 18:09

elprup