Logging and Python bokeh compatibility

Question:

I am using import logging to save changes to my bokeh server and I want to save it to a file with a .log extension, but when I run the bokeh server, the file is not created and the can not save operations to .log file.
There is a part of the code I wrote below.

Could it be that I am making a mistake in the code or bokeh server does it not work in accordance with logging?

import logging
LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
logging.basicConfig(filename = "test.log",
                level = logging.DEBUG,
                format = LOG_FORMAT,
                filemode="w")
logger = logging.getLogger()
Asked By: Gülsay

||

Answers:

When you use bokeh serve %some_python_file%, the Bokeh server is started right away, but your code is executed only when you actually open the URL that points to the Bokeh document that you fill in that code.

bokeh serve configures logging by using logging.basicConfig as well, and calling this function again does not override anything – that’s just how logging.basicConfig works.

Instead of using logging directly, you should just create and configure your own logger:

LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
file_handler = logging.FileHandler(filename='test.log', mode='w')
file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
logger = logging.getLogger(__name__)
logger.addHandler(file_handler)
logger.setLevel(logging.DEBUG)

logger.info('Hello there')
Answered By: Eugene Pakhomov

Eugene’s answer is correct. Calling logging.basicConfig() for a second time does not have any effect. Nevertheless, if you are using python >= 3.8 then you can use force=True which will disable all existing logging handlers and setup a new one. This practically means that your own logging.basicCOnfig() will just work:

logging.basicConfig(..., force=True)

docs

Answered By: pmav99
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.