I have a service that is responsible for 2 flows: A and B. Those flows are connected but I want to log each flow in a different log file.
I thought using the following config file:
[loggers]
keys=root,A,B
[handlers]
keys=file_handler
[formatters]
keys=full
[logger_A]
level=INFO
handlers=fileHandler
[logger_B]
level=INFO
handlers=fileHandler
[logger_root]
level=INFO
handlers=fileHandler
[handler_fileHandler]
class=FileHandler
level=INFO
formatter=full
args=('%(logfilename)s','%(permissions)s','%(encoding)s',)
[formatter_full]
format=[%(asctime)s] [%(levelname)s] --- [%(funcName)s] [P%(process)d][%(threadName)s - %(thread)d]- %(message)s
datefmt='%Y-%m-%d %H:%M:%S'
From what I understood there isn't any way to send those args to the fileHandler dynamically during runtime, right? The handler has the same attributes for all loggers the difference is the destination file that the logger writes to.
I thought about configuring a function that will get as an input the logger name and the destination file and will return me the logger - it is something that was suggested in Logging to two files with different settings:
import logging
def getLoggerToFile(loggerName,filePath,fileMode,fileHandler=None,level=logging.INFO):
logger = logging.getLogger(loggerName)
if len(logger.handlers) > 0:
return logger
if(fileHandler is None):
formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] --- [%(funcName)s] '
'[P%(process)d][%(threadName)s - %(thread)d]- %(message)s')
fileHandler = logging.FileHandler(filePath, mode=fileMode)
fileHandler.setFormatter(formatter)
logger.setLevel(level)
logger.addHandler(fileHandler)
return logger
Wanted to hear of any other suggestions and to ask a question:
If I'll use the function, and I'll call the function twice with the same logger name but with different file path, the logger won't be able to write simultaneously to 2 different files, right? So it's the same as creating a config file with 2 loggers and a handler/formatter for each logger.