Python: 记录到多个日志文件

4

目前我将所有内容都记录在一个日志文件中,但我希望将其分开成多个日志文件。我查看了Python文档中的日志记录部分,但他们没有讨论这个问题。

log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
logging.basicConfig(filename=(os.path.join(OUT_DIR, + '-user.log')),
            format=log_format, level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S')

目前我是这样记录日志的。我想要将不同类型的错误或信息记录到不同的日志文件中。目前,当我执行 logging.info('Logging IN')logging.error('unable to login') 时,它们会被记录到同一个日志文件中。我想要将它们分开。我需要创建另一个日志对象来支持记录到另一个文件吗?


你想要实现什么目标?你是严格要求一个原始日志文件的副本,还是想要按日志级别分离?... - Demian Brecht
请参考 http://docs.python.org/2/howto/logging-cookbook.html 中的 logger.addHandler 示例。 - Paulo Scardine
刚刚在问题中添加了更多信息。 - add-semi-colons
2个回答

3

你可以做的事情(我没有深入研究 logging 模块,所以可能有更好的方法)是可能使用流来代替文件对象:

In [1]: class LogHandler(object):
   ...:     def write(self, msg):
   ...:         print 'a :%s' % msg
   ...:         print 'b :%s' % msg
   ...:         

In [3]: import logging
In [4]: logging.basicConfig(stream=LogHandler())
In [5]: logging.critical('foo')
a :CRITICAL:root:foo
b :CRITICAL:root:foo

In [6]: logging.warn('bar')
a :WARNING:root:bar
b :WARNING:root:bar

编辑并进行进一步处理:

假设您的日志文件已经存在,您可以像这样操作:

import logging

class LogHandler(object):
    format = '%(levelname)s %(message)s'
    files = { 
        'ERROR': 'error.log',
        'CRITICAL': 'error.log',
        'WARN': 'warn.log',
    }   
    def write(self, msg):
        type_ = msg[:msg.index(' ')] 
        with open(self.files.get(type_, 'log.log'), 'r+') as f:
            f.write(msg)

logging.basicConfig(format=LogHandler.format, stream=LogHandler())
logging.critical('foo')

这将允许您根据日志信息中的条件将日志拆分为各种文件。如果找不到所需内容,则默认使用 log.log


2
我从docs.python.org/2/howto/logging-cookbook.html创建了这个解决方案。 只需创建两个日志文件处理程序,分配它们的日志级别并将它们添加到您的记录器即可。
import os
import logging

current_path = os.path.dirname(os.path.realpath(__file__))

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)

#to log debug messages                               
debug_log = logging.FileHandler(os.path.join(current_path, 'debug.log'))
debug_log.setLevel(logging.DEBUG)

#to log errors messages
error_log = logging.FileHandler(os.path.join(current_path, 'error.log'))
error_log.setLevel(logging.ERROR)

logger.addHandler(debug_log)
logger.addHandler(error_log)

logger.debug('This message should go in the debug log')
logger.info('and so should this message')
logger.warning('and this message')
logger.error('This message should go in both the debug log and the error log')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,