简体   繁体   English

Python:logging.streamhandler没有将日志发送到stdout

[英]Python: logging.streamhandler is not sending logs to stdout

I want to use StreamHandler logging handler of python. 我想使用python的StreamHandler日志处理程序。 What i have tried is, 我试过的是,

import logging
import sys
mylogger = logging.getLogger("mylogger")
h1 = logging.StreamHandler(stream=sys.stdout)
h1.setLevel(logging.DEBUG)

mylogger.addHandler(h1)

# now trying to log with the created logger
mylogger.debug("abcd") # <no output>
mylogger.info("abcd") # <no output>
mylogger.warn("abcd") # abcd

Am i missing something ? 我错过了什么吗? Or doing any wrong ? 或者做错了什么? Why INFO and DEBUG level logs are not coming on STDOUT ? 为什么INFO和DEBUG级别日志不会出现在STDOUT上?

You have to set the level of the logger, not only the level of the handler: 您必须设置记录器的级别,而不仅仅是处理程序的级别:

mylogger.setLevel(logging.DEBUG)

Here is a nice graphic of the logging workflow, where you can see that either the logger and the handler check for the log level: 这是一个很好的日志工作流图形,您可以看到记录器和处理程序检查日志级别:

http://docs.python.org/2/howto/logging.html#logging-flow http://docs.python.org/2/howto/logging.html#logging-flow

The default logLevel is WARNING , so even if you set the level of your handler to DEBUG , the message will not get through, since your logger suppresses it (it's also by default WARNING ). 默认的logLevelWARNING ,因此即使您将处理程序的级别设置为DEBUG ,该消息也无法通过,因为您的记录器会对其进行抑制(默认情况下也是WARNING )。

By the way, you can do some basic formatting with Formatter : 顺便说一下,你可以用Formatter做一些基本的Formatter

import logging
import sys

mylogger = logging.getLogger("mylogger")

formatter = logging.Formatter('[%(levelname)s] %(message)s')

handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)

mylogger.addHandler(handler)
mylogger.setLevel(logging.DEBUG)

mylogger.debug("This is a debug message.")
mylogger.info("Some info message.")
mylogger.warning("A warning.")

Will give you the output 会给你输出

[DEBUG] This is a debug message.
[INFO] Some info message.
[WARNING] A warning.

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

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