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?
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
You should take a look at the python documentation. Using multiple logger seems to be the recommended way.
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