简体   繁体   English

Python:在其他输出之前记录打印到控制台的注释

[英]Python: logging comments printed to console before other outputs

I have been trying to understand logging in python.我一直在尝试了解 python 中的日志记录。 I have an init module, two other modules and a main module.我有一个init模块、两个其他模块和一个主模块。 For some reason, when I run my module, log details jump the code flow and are printed first before the other outputs出于某种原因,当我运行我的模块时,日志详细信息会跳转代码流并在其他输出之前首先打印

Could someone tell me why this is happening有人能告诉我为什么会这样吗

this is in __init__.py这是在__init__.py

from dir1.mod1 import FirstClass
from dir1.mod2 import SecondClass

logger = logging.getLogger(__name__)

logger.setLevel(logging.DEBUG)
f_handler=logging.FileHandler('python_logs.log')
f_handler.setLevel(logging.DEBUG)
c_handler = logging.StreamHandler()
c_handler.setLevel(logging.ERROR)

f_formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
c_formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')

f_handler.setFormatter(f_formatter)
c_handler.setFormatter(c_formatter)

logger.addHandler(f_handler)
logger.addHandler(c_handler)

This is in other two modules(written inside __init__() of the resp class这是在其他两个模块中(写在 resp 类的__init__()

self.logger = logging.getLogger(__name__)

snippet of addn() function defined inside one of the module在模块之一中定义的 addn() 函数片段

def addn(self):
    z=self.x +self.y
    print('sum is '+z)
    self.logger.error('incrementing number!')
    self.logger.info('Still incrementing number!!')
    return z

And my main modules(which I run) has this:我的主要模块(我运行的)有这个:

from dir1.mod1 import FirstClass
from dir1.mod2 import SecondClass

number = FirstClass(2,2)
print('addition results')
number.addn()

I was expecting a output as below我期待输出如下

addition results加法结果

sum is 3总和是 3

dir1.mod1 - ERROR - incrementing number! dir1.mod1 - 错误 - 数字递增!

But what I got was但我得到的是

dir1.mod1 - ERROR - incrementing number! dir1.mod1 - 错误 - 数字递增!

dir1.mod1 - ERROR - incrementing number! dir1.mod1 - 错误 - 数字递增!

addition results:加法结果:

sum is 3总和是 3

Why is the log message printed first jumping out of code flow?为什么首先打印的日志信息跳出代码流? And also could someone tell me why log message gets printed twice??还有谁能告诉我为什么日志消息会打印两次?

U can try disable the propagate property of your logger. 您可以尝试禁用记录器的传播属性。

Propagate : If this attribute 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. 传播 :如果此属性的计算结果为true,则除了连接到此记录器的任何处理程序之外,记录到此记录器的事件将传递给更高级别(祖先)记录器的处理程序。 Messages are passed directly to the ancestor loggers' handlers - neither the level nor filters of the ancestor loggers in question are considered. 消息直接传递给祖先记录器的处理程序 - 既不考虑有问题的祖先记录器的级别也不考虑过滤器。

This is an example of init logger that uses file and stdout with different debug level: 这是使用具有不同调试级别的file和stdout的init logger的示例:

def init_logger_singleton():

    global logger

    logger = logging.getLogger(name='loggerName')
    logger.propagate = False
    logger.setLevel(10)
    formatter = logging.Formatter(
        '\t%(message)s'
    )

    filehandler = logging.StreamHandler()
    filehandler.setLevel(40)
    filehandler.setFormatter(formatter)
    logger.addHandler(filehandler)

I used number to define the log level, but 10 = DEBUG and 40 = ERRO. 我使用数字来定义日志级别,但是10 = DEBUG和40 = ERRO。 More information at this link. 有关此链接的更多信息

Python StreamHandler will log to stderr by default while you print statements goes to stdout. 默认情况下,当您将打印语句转到stdout时,Python StreamHandler将登录到stderr。 Those are two different pipelines and the ordering isn't guaranteed between them. 这是两个不同的管道,它们之间无法保证订购。

To ensure proper ordering start by sending all output to the same pipe. 通过将所有输出发送到同一管道来确保正确的订购。 For example you could add the file=sys.stderr argument to your print statements. 例如,您可以将file=sys.stderr参数添加到print语句中。

您还可以将参数sys.stdout添加到您的流处理程序,因此print和记录器事件都将传递到一个通道。

stream_handler = logging.StreamHandler(sys.stdout)

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

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