Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging: how to set a maximum log level for a handler

Tags:

python

logging

With logging library you can log to file. You have to set the file handler log level. Any log with level equal or higher than the specified level will be logged to file.

But what if I want to log errors and exceptions to a file myapp_errors.log, infos to another file myapp_info.log and any other log to another file myapp_debug.log? The only option is to create three loggers?

like image 697
Marco Sulla Avatar asked Mar 31 '16 15:03

Marco Sulla


2 Answers

You can add filters to filehandlers. This way you can redirect specific levels to different files.

import logging

class LevelFilter(logging.Filter):
    def __init__(self, low, high):
        self._low = low
        self._high = high
        logging.Filter.__init__(self)
    def filter(self, record):
        if self._low <= record.levelno <= self._high:
            return True
        return False


logging.basicConfig(level=logging.DEBUG)

log = logging.getLogger('foo')
error_handler = logging.FileHandler('error.log', 'a')
error_handler.addFilter(LevelFilter(40, 40))
warn_handler = logging.FileHandler('warn.log', 'a')
warn_handler.addFilter(LevelFilter(30, 30))
log.addHandler(error_handler)
log.addHandler(warn_handler)

log.debug('debug')
log.info('info')
log.warn('warn')
log.error('error')

Warnings will go to warn.log, errors to error.log. All other levels will not be stored in a file.

Example:

$ python log.py
DEBUG:foo:debug
INFO:foo:info
WARNING:foo:warn
ERROR:foo:error
$ tail -n +1 *.log
==> error.log <==
error

==> warn.log <==
warn
like image 103
Schore Avatar answered Nov 12 '22 13:11

Schore


You should take a look at the python documentation. Using multiple logger seems to be the recommended way.

like image 20
n00dl3 Avatar answered Nov 12 '22 15:11

n00dl3