Is it possible to have multiple logging handlers referring to the same log file in python logging configuration. I can make it work by having one more handler handler_two added to the handlers object, but this seems to be a boilerplate.
"handler_two": {
"level": "DEBUG",
"class": "logging.handlers.TimedRotatingFileHandler",
"formatter": "verbose",
"filename": "{}/abc.log".format(log_folder),
"when": "midnight",
"backupCount": 10,
"encoding": "utf8"
},
logging.conf -
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"verbose": {
"format": "%(asctime)s %(name)s %(levelname)s (PID: %(process)d) %(message)s",
"datefmt": "%d/%m/%Y %I:%M:%S %p %Z"
},
"simple": {
"format": "%(asctime)s %(name)s %(levelname)s > %(message)s"
}
},
"handlers": {
"handler_one": {
"level": "DEBUG",
"class": "logging.handlers.TimedRotatingFileHandler",
"formatter": "verbose",
"filename": "{}/abc.log".format(log_folder),
"when": "midnight",
"backupCount": 10,
"encoding": "utf8"
},
"error": {
"level": "ERROR",
"class": "logging.handlers.TimedRotatingFileHandler",
"formatter": "verbose",
"filename": "{}/error.log".format(log_folder),
"when": "midnight",
"backupCount": 10,
"encoding": "utf8"
}
},
"root": {
"level": "ERROR",
"handlers": [
"error"
]
},
"loggers": {
"handler_one": {
"level": "DEBUG",
"handlers": [
"handler_one"
],
"propagate": "false"
},
}
}
It is possible to achieve that by opening the file stream yourself and passing it to the stream handler, as in the following:
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
stream = open("test.log", "a")
handler_1 = logging.StreamHandler(stream)
logger.addHandler(handler_1)
handler_2 = logging.StreamHandler(stream)
logger.addHandler(handler_2)
logger.info("test log")
The test.log file will then have content:
test log
test log
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With