python记录到多个目标 [英] python logging to multiple destination

查看:104
本文介绍了python记录到多个目标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手.现在,我需要利用日志记录,这是我做的实验:

I am new to Python. I now need to make use of logging and here is the experiment I did:

我有2个文件:

logtest_1.py,logtest_2.py

logtest_1.py, logtest_2.py

logtest_1.py:

logtest_1.py:

    import logging
    from logtest_2 import loglib

    format = '%(asctime)s: %(levelname)s: %(message)s'
    logging.basicConfig(format=format,level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    logger.info('Before calling loglib...')
    loglib()
    logger.info('Loglib done.')

logtest_2.py: 导入日志 从logging.handlers导入TimedRotatingFileHandler 导入时间

logtest_2.py: import logging from logging.handlers import TimedRotatingFileHandler import time

def loglib():
    logger_2 = logging.getLogger(__name__)

    logger_3 = logging.getLogger('TimeRotateLogger')
    logger_3.setLevel(logging.DEBUG)
    handler = TimedRotatingFileHandler('timerotate.log',
                                        when='s',
                                        interval=2,
                                        backupCount=10)
    logger_3.addHandler(handler)

    logger_2.info('This is a log from logtest_2.')

    time.sleep(1)
    for i in range(5):
        logger_3.info('Rotation test...')
        time.sleep(2)

我尝试使用logger_3将信息写入那些时间循环文件.实际上,这可行.但是,它也会打印到屏幕上:

I try to use logger_3 to write info to those time rotation files. Actually, this works. However, it also prints out to the screen:

2015-02-16 15:26:34,010: INFO: Before calling loglib...
2015-02-16 15:26:34,011: INFO: This is a log from logtest_2.
2015-02-16 15:26:35,019: INFO: Rotation test...
2015-02-16 15:26:37,029: INFO: Rotation test...
2015-02-16 15:26:39,039: INFO: Rotation test...
2015-02-16 15:26:41,049: INFO: Rotation test...
2015-02-16 15:26:43,059: INFO: Rotation test...
2015-02-16 15:26:45,070: INFO: Loglib done.

我只希望logger_3登录到那些文件.如何防止它打印到屏幕上?

I only want logger_3 to log into those files. How can I prevent it from printing to the screen?

此外,为什么会这样呢?我已经将处理程序交给logger_3,该处理程序可以写入文件.

Also, why this is happening? I've already given the handler to logger_3 which writes to files.

如果我真的想将logging.basicConfig(format=format,level=logging.DEBUG)保留在logtest_1.py中,该怎么办?

If I really want to keep logging.basicConfig(format=format,level=logging.DEBUG) in the logtest_1.py, what should I do?

推荐答案

之所以会发生这种情况,是因为默认情况下,您的logger_3也是

This happens because your logger_3 by default also propagates log events to its parent logger, the root logger.

如果您使用 basicConfig() ,则是根记录器默认情况下会附加StreamHandler,这也会导致您的消息也出现在控制台上.

If you use basicConfig(), the root logger will have a StreamHandler attached to it by default which causes your message to also end up on the console.

为防止这种情况,您可以设置logger_3.propagate = False,或仅将处理程序直接附加到根记录器(这是最常用的设置),然后使用

To prevent this, you can either set logger_3.propagate = False, or only attach handlers directly to your root logger (which is the most common used setup) and use logging levels and filters to control where your output goes.

仅将处理程序附加到根记录器的示例如下:

An example for only attaching your handlers to the root logger could look like this:

import logging
from logging.handlers import TimedRotatingFileHandler


format = '%(asctime)s: %(levelname)s: %(message)s'
logging.basicConfig(format=format, level=logging.INFO)
logger = logging.getLogger(__name__)

handler = TimedRotatingFileHandler('timerotate.log',
                                   when='s',
                                   interval=2,
                                   backupCount=10)
handler.setLevel(logging.DEBUG)
logging.root.addHandler(handler)

logger.info('This will end up on console and in timerotate.log')
logger.debug('This will only end up in timerotate.log')

basicInfo()将级别为INFOStreamHandler附加到登录到stdout的根记录器-但仅级别为

basicInfo() attaches a StreamHandler with level INFO to the root logger that logs to stdout - but only messages with level INFO or higher.

然后再附加一个级别为DEBUG的处理程序,这样它将把级别为DEBUG或更高级别的每条消息记录到timerotate.log.这是一个非常简单的示例,它使用不同的日志级别来确定输出最终到达的位置-使用这种方法,您无法将特定的 only 语句发送到控制台,而不能将另一条 only 到文件.

You then attach a second handler with level DEBUG, so it will log every message with level DEBUG or higher to timerotate.log. This is a very simple example that uses different log levels to determine where output ends up - using this approach you can't send a particular statement only to the console, and a different one only to a file.

如果您需要更精细的控制,则可以例如在 extra关键字参数,在登录时使用

If you need more fine grained control, you could for example pass some data in the extra keyword argument when logging, and add a filter to any of your handlers to only emit messages that match certain criteria.

但是,如果您只是想直接从代码中控制一条特定消息应该发送到一个文件,并且只发送到该文件,那么将logger_3.propagate设置为False并使用它可能是最简单的您已经描述的设置.

But, if you simply want to be able to directly control from your code that a particular message should go to a file, and only that file, then it's probably easiest to simply set logger_3.propagate to False, and use the setup you already described.

这篇关于python记录到多个目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆