Python: logging.streamhandler is not sending logs to stdout

Question:

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 ?

Asked By: Aashish P

||

Answers:

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.
Answered By: tamasgal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.