How to define logging in one place in Python?

PythonLearner :

I am new Python and I want to define the following logging code in python in one place so that it can be used in other python files(class or non-class). In case of Java, we use log4j or slf4j as part of jar files and we simply define as Logger logger = Logger.getLogger("class name"), I want achieve exactly like this so that I can use loger in any python module/s. Currently I define the config in all the classes.

import logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("debug.log"),
        logging.StreamHandler()
    ]
)

I have also gone through this SO link Using logging in multiple modules

Also please suggest the most recommended approach for medium to large project having more number of python files.

Sambit :

As per this link https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/, the author has mentioned a better practice. There may be better recommended approach. You have to do in the following manner.

  1. Define logging.json file as mentioned in the link.
  2. Define a python file called LogSetup.py and add below the code.
def setup_logging(default_path='logging.json', default_level=logging.DEBUG, env_key='LOG_CFG'):
    """Setup logging configuration"""
    path = default_path
    value = os.getenv(env_key, None)
    if value:
        path = value
    if os.path.exists(path):
        with open(path, 'rt') as f:
            config = json.load(f)
        logging.config.dictConfig(config)
    else:
        logging.basicConfig(level=default_level)
  1. Call the above file like this LogSetup.setup_logging() in the main method. I provide below the code snippet.

logger = logging.getLogger(name)

if __name__ == '__main__':
    LogSetup.setup_logging()
    logger.debug("This is a debug message ...")

It looks good for me, others may recommend the better approaches.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=420084&siteId=1