使用默认记录器后,Python 2记录器重复行

编程入门 行业动态 更新时间:2024-10-27 22:33:24
本文介绍了使用默认记录器后,Python 2记录器重复行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在处理一段代码,该代码使用其自己的处理程序和格式实例化其自己的记录器.

I am working on a piece of code which instantiates its own logger with its own handlers and format.

现在,我添加了一个直接使用日志记录模块的库,它使我的记录器搞砸了-原始记录器开始以不同的格式打印每行两次,而默认记录器什么也不打印.

Now I've added a use of a library which uses the logging module directly and it screws up my logger - The original logger starts printing each line twice in different formats while the default logger prints nothing at all.

有什么建议吗? MCVE:

Any suggestions? MCVE:

import sys import logging log = logging.getLogger('foo') log.addHandler(logging.StreamHandler(sys.stdout)) log.setLevel(logging.DEBUG) log.info("works once") logging.info("Isn't printed") log.info("printed twice with different format")

输出:

works once printed twice with different format INFO:foo:printed twice with different format

似乎也不是默认记录器以某种方式向我的记录器实例添加了额外的处理程序:

It also doesnt seem like the default logger somehow adds an extra handler to my logger instance:

> print log.handlers [<logging.StreamHandler object at 0x7f5d14314990>]

我无法更改包含的模块...

I can't change the module I've included...

推荐答案

在挖掘和挖掘之后,我终于找到了一些文档来救了我!

After digging and digging, I finally found the bit of documentation that saved me!

Logger.propagate

如果此结果为true,则事件记录到此 记录器将传递给更高级别的处理程序(祖先) 记录器,以及与此记录器相连的所有处理程序.留言内容 直接传递给祖先记录程序的处理程序- 级别或相关祖先记录器的过滤器都不会考虑.

If this evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered.

如果结果为假,则日志消息不会传递到 祖先记录器的处理程序.

If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.

构造函数将此属性设置为True.

The constructor sets this attribute to True.

设置log.propagate = False结束了我的不幸.

通过logging.info第一次使用默认记录器似乎已经初始化了默认记录器,从那一刻起,传播开始起作用.

It would appear that the 1st use of the default logger through logging.info has initialized the default logger and from that moment the propagation started having an effect.

更多推荐

使用默认记录器后,Python 2记录器重复行

本文发布于:2023-11-15 17:33:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1596536.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:记录器   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!