1

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())
spiderplant0
  • 3,872
  • 12
  • 52
  • 91
  • Is it printing the *same line twice* to *both* the console and the file, or is it printing each line once? It's not clear because the question title suggests the former but your comment in the example code suggests the latter. If it's the second case, that's actually expected, I can submit an answer explaining why. Otherwise, well, I only have some ideas to try. – Brett Jul 10 '15 at 20:26
  • @bgrace. Thanks - I have clarified the question. It is the former. I want to print to the log file as well as the console. But I only want it to print to each one. But at the moment I get a duplicate message on both console and log file. – spiderplant0 Jul 10 '15 at 20:53
  • Any chance you are importing this file twice? See for example as in http://stackoverflow.com/questions/4798589/what-could-cause-a-python-module-to-be-imported-twice. I would start troubleshooting by throwing some assertions in there. E.g. before setting the handler, `assert 0 == len(logger.handlers)` — the stack trace will probably point to the second importer here. – Brett Jul 10 '15 at 21:10

1 Answers1

2

Using a config file. e.g. 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.

blakev
  • 4,154
  • 2
  • 32
  • 52