Search code examples
pythonloggingmoduleglobal-variablespython-logging

Python: logging module - globally


I was wondering how to implement a global logger that could be used everywhere with your own settings:

I currently have a custom logger class:

class customLogger(logging.Logger):
   ...

The class is in a separate file with some formatters and other stuff. The logger works perfectly on its own.

I import this module in my main python file and create an object like this:

self.log = logModule.customLogger(arguments)

But obviously, I cannot access this object from other parts of my code. Am i using a wrong approach? Is there a better way to do this?


Solution

  • Use logging.getLogger(name) to create a named global logger.

    main.py

    import log
    logger = log.setup_custom_logger('root')
    logger.debug('main message')
    
    import submodule
    

    log.py

    import logging
    
    def setup_custom_logger(name):
        formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(module)s - %(message)s')
    
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
    
        logger = logging.getLogger(name)
        logger.setLevel(logging.DEBUG)
        logger.addHandler(handler)
        return logger
    

    submodule.py

    import logging
    
    logger = logging.getLogger('root')
    logger.debug('submodule message')
    

    Output

    2011-10-01 20:08:40,049 - DEBUG - main - main message
    2011-10-01 20:08:40,050 - DEBUG - submodule - submodule message