0

I have created a logging module in my python package, and I am using the logging module to get the console logging instance for other files in the package. Now I want to create a toggle variable so that, I can disable or enable the console logging in the entire package. Please suggest me way to implement what i have described.

My sample package structure:

package/
|_ __init__.py
|_ logger.py
|_ moduleA.py
|_ moduleB.py

logger.py

import logging

""" can I create any get/set kind of implementation here to control a toggle variable 
    based on which I decide the log level to be DEBUG or ERROR for the entire package  """ 


def getLogger(name):
    logger = logging.getLogger(name)
    handler = logging.StreamHandler()
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    return logger

I am using this logger something like below in other modules

log = logger.getLogger(__name__)
log.info("Hello!")

1 Answers1

0

A common way to accomplish what you want is to define an environment variable such as LOGLEVEL and use it when calling setLevel() or basicConfig().

Example:

import os

logger.setLevel(os.environ.get("LOGLEVEL", "DEBUG"))

Side note: There is typically no need to create a getLogger function of your own to allow all of your modules to share the root logger. You can accomplish the same thing by initializing the root logger in you application entry point, and using __name__ variable when calling logging.getLogger() in your modules. Here is a good explanation regarding that approach.

rhurwitz
  • 2,557
  • 2
  • 10
  • 18
  • Thanks for the solution. If I want to import this package in a different program do I have to create and set the environment variable from the program before importing this module ? – headoftheport Mar 26 '21 at 13:23
  • If you are developing a library (versus and application) there is [a specific way to configure logging](https://docs.python.org/3/howto/logging.html#library-config) that you should follow. If you are developing an application you should probably change the default level to ERROR so you don't spam your users. – rhurwitz Mar 26 '21 at 16:36
  • 1
    Okay. This is really helpful. Thanks for the side note as well. It saved me from writing the redundant file to configure the root logger. – headoftheport Mar 27 '21 at 15:00