user1187968
user1187968

Reputation: 8036

Logging with info level doesn't produce any output

I ran the following using both the Python shell, and run it as a Python file from the command line. I don's see my log output at all.

import logging

formatter = logging.Formatter('%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s')

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)

logger = logging.getLogger()
logger.addHandler(stream_handler)
logger.info(("info logging"))

Upvotes: 1

Views: 46

Answers (4)

chepner
chepner

Reputation: 532333

A logger and a handler can have different levels. You have only set the level for the handler, not the logger itself.

import logging

formatter = logging.Formatter('%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s')

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)

logger = logging.getLogger()
logger.setLevel(logging.INFO)  # Required
logger.addHandler(stream_handler)
logger.info(("info logging"))

Upvotes: 0

noufel13
noufel13

Reputation: 663

You need to set the level of your logger,

logger.setLevel(logging.INFO)

Below statement can be removed from your code,

stream_handler.setLevel(logging.INFO)

Upvotes: 0

m_____z
m_____z

Reputation: 1591

Your logging output was almost correct with the exception of setLevel. The logging level needs to be defined on the logger instance instead of the handler instance. Your code therefore only needs a very small tweak to make it work:

import logging

formatter = logging.Formatter(
    '%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s'
)

stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)

logger = logging.getLogger()
logger.addHandler(stream_handler)
logger.setLevel(logging.INFO)

logger.info("info logging")

This piece of code produces the following output:

2019-08-21 15:04:55,118,118 INFO     [testHandler.py:11] info logging

Note, I also removed the double brackets on the logger.info call as these are not necessary.

Upvotes: 1

BookYourLuck
BookYourLuck

Reputation: 330

Use logging.basicConfig() to initialize the logging system.

Upvotes: 0

Related Questions