简体   繁体   中英

Python: logging.streamhandler is not sending logs to stdout

I want to use StreamHandler logging handler of python. 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 ?

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

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 ).

By the way, you can do some basic formatting with 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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