2

I am using python 2.7 for a multi-module project. As mentioned here I have configured logging in my main.py like below

logging.basicConfig(
    format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
    datefmt='%d-%m-%Y:%H:%M:%S',
    filename='/home/ubuntu/logs/centralized_upgrade.log',
    level=logging.INFO)

In every other module wherever I have to log I am just making a call like below

import logging
...
logging.info('Hello World')

But the doubt I am having is if in some module if root logger is again reconfigured (may be something like below)

logging.basicConfig(
        format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s',
        datefmt='%d-%m-%Y:%H:%M:%S',
        filename='/home/ubuntu/logs/module.log',
        level=logging.INFO)

then all log messages will start going into the new file. Can someone let me know what is the best way to handle this? How can I prevent the reconfiguration of root logger? My intention is that logging configuration should stay same as defined in main.py irrespective of any reconfiguration done in any child modules.

In many places, it is recommended to not use root logger and define a logger like as mentioned here. But as per my understanding in this case also if some module configures the root logger then log may go to a different file as all loggers inherit from root logger.

martineau
  • 119,623
  • 25
  • 170
  • 301
tuk
  • 5,941
  • 14
  • 79
  • 162
  • 2
    Not a complete answer, but: [`logging.basicConfig`](https://docs.python.org/3/library/logging.html#logging.basicConfig) will not do anything if the root logger already has handlers configured for it. So if it's invoked multiple times, only the first one will apply the given configuration to the root logger. – Lukas Graf Sep 22 '18 at 16:48
  • 2
    The real (if useless) answer is “don’t use modules that are so careless as to unconditionally alter global state”, whether it’s the root logger, the process’s signal dispositions, or the standard streams. – Davis Herring Sep 22 '18 at 20:47
  • Thanks @LukasGraf this will work for me now. – tuk Sep 23 '18 at 05:14

1 Answers1

0

Posting the comment of @Lukas Graf as the answer here

Not a complete answer, but: logging.basicConfig will not do anything if the root logger already has handlers configured for it. So if it's invoked multiple times, only the first one will apply the given configuration to the root logger.

tuk
  • 5,941
  • 14
  • 79
  • 162