简体   繁体   English

从模块记录器登录到sys.stdout

[英]Log to sys.stdout from a module logger

I have the following simple test script: 我有以下简单的测试脚本:

import logging
import sys


logger = logging.getLogger(__name__)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s'$
logger.addHandler(handler)


logger.info('Hello World!')
logger.warning('Bad!')

I run this script with python test.py in the command line. 我在命令行中使用python test.py运行此脚本。 I get: 我得到:

__main__ - WARNING - Bad!

When I expected to get: 当我期望得到:

__main__ - WARNING - Bad!
__main__ - INFO - Hello World!

Eg I expected both the info and warning log messages to get printed to the console window, but only the warning message did. 例如,我希望infowarning日志消息都可以打印到控制台窗口,但是只有warning消息可以。 How come? 怎么会?

This should work? 这应该工作吗?

import logging
import sys


logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter('%(name)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)


logger.info('Hello World!')
logger.warning('Bad!')

You should be setting the setLevel on the logger object. 您应该在logger对象上设置setLevel

Thanks 谢谢

I think What is the point of setLevel in a python logging handler? 我认为python日志记录处理程序中setLevel的意义是什么? contains answer. 包含答案。

You need to setLevel on logger itself too, its level (default WARNING) will not allow messages from it's handlers with lower level than set in parent-logger. 您还需要在logger本身上设置setLevel ,它的级别(默认为WARNING)将不允许来自其处理程序的消息的级别低于在父记录器中设置的级别。

Handler is there to filter messages. 处理程序在那里过滤消息。

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

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