简体   繁体   中英

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

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.

使用 logging.basicConfig() 来初始化日志系统。

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)

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

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