简体   繁体   中英

Python logger is printing messages twice on both the PyCharm console and the log file

Similar questions were caused by the logger getting called twice. So maybe in my case it is caused by the second getLogger() . Any ideas how I can fix it?

import logging
import logging.handlers

logger = logging.getLogger("")

logger.setLevel(logging.DEBUG)

handler = logging.handlers.RotatingFileHandler(
    "the_log.log", maxBytes=3000000, backupCount=2)

formatter = logging.Formatter(
    '[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# This is required to print messages to the console as well as the log file.
logging.getLogger().addHandler(logging.StreamHandler())

Using a config file. eg logging.config.fileConfig('logging.ini')

[logger_root]
level=ERROR
handlers=stream_handler

[logger_webserver]
level=DEBUG
handlers=stream_handler
qualname=webserver
propagate=0

You have to set logger.propagate = 0 ( Python 3 Docs ) when you're configuring the root logger and using non-root-loggers at the same time.

I know this was asked a long time ago, but it's the top result on DuckDuckGo.

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