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?
Use logging. getLogger(name) to create a named global logger. Since you have to re-define the logger in your submodule.py , then the global definition is not such. Likewise one could have just re-initialised the logger in every sub-module reading from a config file (actually requiring even fewer key strokes).
Python comes with a logging module in the standard library that provides a flexible framework for emitting log messages from Python programs. This module is widely used by libraries and is the first go-to point for most developers when it comes to logging.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With