Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 295
cwoebker Avatar asked Oct 01 '11 17:10

cwoebker


People also ask

How do I use global logger in Python?

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).

What is logging module in Python?

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.


1 Answers

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 
like image 156
koehlma Avatar answered Oct 04 '22 01:10

koehlma