Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple handlers to same log file in python logging

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"
    },
  }
}
like image 250
Pro Avatar asked Jun 06 '26 01:06

Pro


1 Answers

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
like image 112
cicolus Avatar answered Jun 08 '26 16:06

cicolus