繁体   English   中英

Python:登录到多个日志文件

[英]Python: Log to multiple log files

目前,我已将所有内容都记录到一个日志文件中,但我想将其分离到多个日志文件中。 我查看了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')将转到相同的日志文件。 我想分开他们。 我需要创建另一个日志记录对象来支持登录到另一个文件吗?

您可能/可能要做的事情(我没有对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

我从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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM