使用 QueueHandler 和 QueueListener 的 Python 日志记录 (logutils)

标签 python logging queue multiprocessing

多进程 python 应用程序需要日志记录。使用队列似乎是最好的解决方案。 logutils 库提供了这一点。

是否可以为两个处理程序独立设置日志级别?例如,在下面的测试中,我希望 STREAM 1 有 WARNING 消息,STREAM 2 有 INFO 消息。在代码末尾的测试日志中,创建了一条不应从 STREAM 1 处理程序(警告)输出到控制台的信息消息。但是,它会输出到两个处理程序。

作为引用,我一直在使用这个页面http://plumberjack.blogspot.co.uk/2010/09/improved-queuehandler-queuelistener.html由库的作者 Vinay Sajip 编写。

# System imports
import logging
import logging.handlers
try:
    import Queue as queue
except ImportError:
    import queue

# Custom imports
from logutils.queue import QueueHandler, QueueListener

# Get queue
q = queue.Queue(-1)

# Setup stream handler 1 to output WARNING to console
h1 = logging.StreamHandler()
f1 = logging.Formatter('STREAM 1 WARNING: %(threadName)s: %(message)s')
h1.setFormatter(f1)
h1.setLevel(logging.WARNING) # NOT WORKING. This should log >= WARNING

# Setup stream handler 2 to output INFO to console
h2 = logging.StreamHandler()
f2 = logging.Formatter('STREAM 2 INFO: %(threadName)s: %(message)s')
h2.setFormatter(f2)
h2.setLevel(logging.INFO) # NOT WORKING. This should log >= WARNING

# Start queue listener using the stream handler above
ql = QueueListener(q, h1, h2)
ql.start()

# Create log and set handler to queue handle
root = logging.getLogger()
root.setLevel(logging.DEBUG) # Log level = DEBUG
qh = QueueHandler(q)
root.addHandler(qh)

root.info('Look out!') # Create INFO message

ql.stop()

最佳答案

您可以使用从 Python 3.5 版添加到 QueueListener 初始化程序的 respect_handler_level 参数,这样监听器就会尊重处理程序的各个级别。

来自 QueueListener's doc :

If respect_handler_level is True, a handler’s level is respected (compared with the level for the message) when deciding whether to pass messages to that handler; otherwise, the behaviour is as in previous Python versions - to always pass each message to each handler.

在您的情况下,您应该将 QueueListener 的初始化替换为:

ql = QueueListener(q, h1, h2, respect_handler_level=True)

关于使用 QueueHandler 和 QueueListener 的 Python 日志记录 (logutils),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25585518/

相关文章:

python - 如何在 python 中有效地合并两个具有容差的数据帧

logging - 登录J2ME

c# - 无法将 Serilog 配置代码行转换为 json 配置

python - 如何在 python 3 中运行 shellcode?

python - 如何在Python中绘制条形图

c# - 自定义 TraceListener 和多条消息

c++ - Mat队列中的访问冲突

asp.net - 使用数据库或 MSMQ 进行排队?

javascript - 检查 JavaScript setTimeout 是否已触发

python - Qhull 凸包要求我输入至少 3 个点