1

I'm using python's logging module. I've initialized it as:

import logging
logger = logging.getLogger(__name__)

in every of my modules. Then, in the main file:

logging.basicConfig(level=logging.INFO,filename="log.txt")

Now, in the app I'm also using WSGIServer from gevent. The initializer takes a log argument where I can add a logger instance. Since this is an HTTP Server it's very verbose.

I would like to log all of my app's regular logs to "log.txt" and WSGIServer's logs to "http-log.txt".

I tried this:

logging.basicConfig(level=logging.INFO,filename="log.txt")
logger = logging.getLogger(__name__)

httpLogger = logging.getLogger("HTTP")
httpLogger.addHandler(logging.FileHandler("http-log.txt"))
httpLogger.addFilter(logging.Filter("HTTP"))

http_server = WSGIServer(('0.0.0.0', int(config['ApiPort'])), app, log=httpLogger)

This logs all HTTP messages into http-log.txt, but also to the main logger.

How can I send all but HTTP messages to the default logger (log.txt), and HTTP messages only to http-log.txt?

EDIT: Since people are quickly jumping to point that this Logging to two files with different settings has an answer, plese read the linked answer and you'll see they don't use basicConfig but rather initialize each logger separately. This is not how I'm using the logging module.

divibisan
  • 11,659
  • 11
  • 40
  • 58
hjf
  • 453
  • 5
  • 16
  • Duplicate of [https://stackoverflow.com/questions/11232230](https://stackoverflow.com/questions/11232230/logging-to-two-files-with-different-settings) – yorodm Aug 24 '18 at 15:28
  • None of those use basicConfig or module-level logging. Please don't be so dupe-happy and take time to read the questions. – hjf Aug 24 '18 at 15:33
  • 1
    @jonrsharpe Not sure about the duplicate. The question and answers there do not deal with two loggers along the same branch of the logging tree. – user2390182 Aug 24 '18 at 15:41

1 Answers1

3

Add the following line to disable propagation:

httpLogger.propagate = False

Then, it will no longer propagate messages to its ancestors' handlers which includes the root logger for which you have set up the general log file.

user2390182
  • 72,016
  • 6
  • 67
  • 89