1

I have implemented the logging using python standard module(I refered python offical docs). I have created a separate logger.py file and return logger from this. In different modules I have imported and used for logging purpose.

Now I want to have a functionality that will enable/disable or on/off the logging. For this I am thinking to define a boolean flag, since I have many files this approach forcing me to write if condition at each line wherever I am logging.

Is there a better approach to achieve the same task?

winter
  • 467
  • 2
  • 10
  • 2
    That's what [logging levels](https://docs.python.org/3/library/logging.html#logging-levels) are for. – bereal Mar 12 '23 at 16:22

1 Answers1

2

If you use standard Python logging then you can use logging.disable(), for example:

import logging

logging.basicConfig(stream=sys.stdout,
                    level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(threadName)s[%(thread)s] %(message)s')

logging.error("some error occurred")   # this is logged
logging.info('some info msg')          # this is logged too
logging.disable(logging.ERROR)         # disable logging for everything that is not higher than ERROR
logging.info('some info msg')          # this is not logged
logging.disable(logging.NOTSET)        # undo disable
logging.info('some info msg')          # this is logged again
v-repin
  • 42
  • 7
  • Hi v-repin, Thanks. Earlier I was setting a flag in config file, If flag is true I was calling/setting `basicConfig()` and returning the logger object to be used in other modules. As you suggested it can be done without flag but must call `basicConfig()`. – winter Mar 12 '23 at 22:32