cwoebker cwoebker - 3 months ago 25
Python Question

Python: logging module - globally

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

I have

class customLogger(logging.Logger):
...


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

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

self.log = log.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?

Answer

Use logging.getLogger(name) to create a named global logger. ( https://docs.python.org/3/library/logging.html#logging.getLogger )

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