Reputation: 449
I would like to put the request logs in different files. Unfortunately, the code below actually creates 2 different .log files, but all the logs end up in the first and the second is completely empty. Can basicConfig be set up so that logs land in different files?
import logging
import time
def example_request_handler(name):
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler(f"{name}.log"),
logging.StreamHandler()])
logging.info(name)
example_request_handler("first_request1")
example_request_handler("secound_request2")
Upvotes: 2
Views: 1869
Reputation: 678
Once logging handlers are added to the logging.basicConfig
they will still remain as they are even after you reconfigure them.
In Python3.8, there was a new force
argument introduced in the logging.basicConfig
. If this keyword argument is specified as true, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.
That would make your function as -
import logging
import time
def example_request_handler(name):
logging.basicConfig(
level=logging.INFO,
force = True,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler(f"{name}.log"),
logging.StreamHandler()])
logging.info(name)
example_request_handler("first_request1")
example_request_handler("second_request2")
Above should log the second_request2
only in the second file.
Please note that removing/adding new logging handlers for every new log is generally a bad idea. If you want to log into n
different files, then consider initializing different loggers for them and keep a mapping of loggers in a manager function which your individual logging functions can use.
Upvotes: 2