简体   繁体   English

使用Python日志记录添加自定义处理程序

[英]add custom handler with Python logging

I have been working on this almost all day couldn't figure what I am missing. 我几乎整天都在努力,无法弄清我的缺失。 I am trying to add a custom handler to emit all log data into a GUI session. 我试图添加一个自定义处理程序以将所有日志数据发送到GUI会话中。 It works but the handler doesn't extend to the submodules and just emits records from the main module. 它可以工作,但是处理程序不会扩展到子模块,而只是从主模块发出记录。 Here is a small snippet I tried 这是我尝试过的一个小片段

I have two files 我有两个档案

# main.py
import logging

import logging_two

def myapp():
    logger = logging.getLogger('myapp')
    logging.basicConfig()
    logger.info('Using myapp')
    ch = logging.StreamHandler()
    logger.addHandler(ch)
    logging_two.testme()
    print logger.handlers

myapp()

Second module 第二模块

#logging_two
import logging

def testme():
    logger = logging.getLogger('testme')
    logger.info('IN test me')
    print logger.handlers

I would expect the logger in logging_two.testme to have the handler I have added in the main module. 我希望logging_two.testme中的logger具有在主模块中添加的处理程序。 I looked at the docs to me it seems this should work but I am not sure if I got it wrong? 我向我看了看文档,看来应该可以,但是我不确定是否弄错了吗?

the result I get is 我得到的结果是

[]
[<logging.StreamHandler object at 0x00000000024ED240>]

In myapp() you are adding the handler to the logger named 'myapp' . myapp()您将处理程序添加到名为'myapp'的记录器中。 Since testme() is getting the logger named 'testme' it does not have the handler since it is a different part of the logging hierarchy. 由于testme()正在获取名为'testme'的记录器,因此它没有处理程序,因为它是记录层次结构的不同部分。

If you just have logger = logger.getLogger() in myapp() then it would work since you are adding the handler to the root of the hierarchy. 如果您在myapp()仅包含logger = logger.getLogger() ,那么它将起作用,因为您将处理程序添加到层次结构的根目录中。

Check out the python logging docs. 查看python日志记录文档。

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

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