记录到Python中的单独文件 [英] Logging to separate files in Python

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

问题描述

我正在使用python的日志记录模块.我已将其初始化为:

I'm using python's logging module. I've initialized it as:

import logging
logger = logging.getLogger(__name__)

在我的每个模块中.然后,在主文件中:

in every of my modules. Then, in the main file:

logging.basicConfig(level=logging.INFO,filename="log.txt")

现在,在应用程序中,我还使用了来自gevent的WSGIServer.初始化程序带有一个log参数,我可以在其中添加一个logger实例.由于这是HTTP服务器,因此非常冗长.

Now, in the app I'm also using WSGIServer from gevent. The initializer takes a log argument where I can add a logger instance. Since this is an HTTP Server it's very verbose.

我想将我的应用程序的所有常规日志记录到"log.txt",并将WSGIServer的日志记录到"http-log.txt".

I would like to log all of my app's regular logs to "log.txt" and WSGIServer's logs to "http-log.txt".

我尝试过:

logging.basicConfig(level=logging.INFO,filename="log.txt")
logger = logging.getLogger(__name__)

httpLogger = logging.getLogger("HTTP")
httpLogger.addHandler(logging.FileHandler("http-log.txt"))
httpLogger.addFilter(logging.Filter("HTTP"))

http_server = WSGIServer(('0.0.0.0', int(config['ApiPort'])), app, log=httpLogger)

这会将所有HTTP消息记录到http-log.txt中,也记录到主记录器中.

This logs all HTTP messages into http-log.txt, but also to the main logger.

如何将除HTTP消息外的所有消息发送到默认记录器(log.txt),而仅将HTTP消息发送到http-log.txt?

How can I send all but HTTP messages to the default logger (log.txt), and HTTP messages only to http-log.txt?

由于人们迅速跳来指出这登录到两个文件设置不同的有一个答案,请阅读链接的答案,您会看到它们不使用basicConfig,而是分别初始化每个记录器.这不是我使用日志记录模块的方式.

Since people are quickly jumping to point that this Logging to two files with different settings has an answer, plese read the linked answer and you'll see they don't use basicConfig but rather initialize each logger separately. This is not how I'm using the logging module.

推荐答案

添加以下行以禁用传播:

httpLogger.propagate = False

然后,它将不再将消息传播到其祖先的处理程序,该处理程序包括您已为其设置常规日志文件的根记录程序.

Then, it will no longer propagate messages to its ancestors' handlers which includes the root logger for which you have set up the general log file.

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

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