How to prevent CherryPy to log to stdout when using the logging module?

61 Views Asked by At

I am using the logging module to log in my application:

import logging
logging.basicConfig(level=logging.INFO)

However, this causes CherryPy to log all lines two times (one in stdout, one in the logging module; which happens to be set to stdout currently):

[02/Jun/2023:11:17:54] ENGINE Bus STARTING
INFO:cherrypy.error:[02/Jun/2023:11:17:54] ENGINE Bus STARTING
[02/Jun/2023:11:17:54] ENGINE Started monitor thread 'Autoreloader'.
INFO:cherrypy.error:[02/Jun/2023:11:17:54] ENGINE Started monitor thread 'Autoreloader'.
[02/Jun/2023:11:17:54] ENGINE Serving on http://0.0.0.0:5005
INFO:cherrypy.error:[02/Jun/2023:11:17:54] ENGINE Serving on http://0.0.0.0:5005
[02/Jun/2023:11:17:54] ENGINE Bus STARTED
INFO:cherrypy.error:[02/Jun/2023:11:17:54] ENGINE Bus STARTED

Of course, I only want the lines that are sent to the logging module, so I can control all logging in my application in the same way.

How can I prevent CherryPy to write the log lines also to stdout?

1

There are 1 best solutions below

2
Vinay Sajip On

In general you should avoid basicConfig() for all but the simplest scenarios (which is what it's intended for), because it gives you fairly limited control of the configuration.

In this case, it's simple - you can just stop the Cherrypy events from being passed to the root logger's handler, which you configured in the basicConfig() call. Here's an example which shows how to do that:

import logging

import cherrypy

logging.basicConfig(level=logging.INFO)
# The next line prevents CherryPy events from being
# passed to the root logger's handler
logging.getLogger('cherrypy').propagate = False

class HelloWorld(object):
    @cherrypy.expose
    def index(self):
        return "Hello, world!"

logging.info('Foo')
cherrypy.quickstart(HelloWorld())

When run, this prints:

INFO:root:Foo
[04/Jun/2023:13:08:30] ENGINE Listening for SIGTERM.
[04/Jun/2023:13:08:30] ENGINE Listening for SIGHUP.
[04/Jun/2023:13:08:30] ENGINE Listening for SIGUSR1.
[04/Jun/2023:13:08:30] ENGINE Bus STARTING
CherryPy Checker:
The Application mounted at '' has an empty config.

[04/Jun/2023:13:08:30] ENGINE Started monitor thread 'Autoreloader'.
[04/Jun/2023:13:08:30] ENGINE Serving on http://127.0.0.1:8080
[04/Jun/2023:13:08:30] ENGINE Bus STARTED