您可以向文件处理程序添加过滤器.这样,您可以将特定级别重定向到不同的文件.
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')
警告将发送到warn.log,错误发送到error.log.所有其他级别都不会存储在文件中.
例:
$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