DoNNie_DarkO
DoNNie_DarkO

Reputation: 367

Set up a python logger configuration through config file

I have a root logger object that I am passing to another module through init calls.

Root_Script.py

import logging
import module

global logger
*initialize logger*

#call module.py and pass the logger to it
module.LOG_TEST(logger)

Module.py

import logging

class LOG_TEST(logger):
  self.logger=logger
  ## want to set up a log level for this particular logger ##

So I have a group of such modules for which I want to set up a different logger configuration. Like i want to set LogLevel to ERROR for these modules.

Now i want to use a config file which i can call in each of these modules and it should change the log levels. So I went through the Logging Documentation and followed it religously.

I used

self.logger=logger.getLogger()
self.logger.setLevel(logging.ERROR)

to achieve this but it doesn't work. Can anyone point out to me how can I set up this with a config file and what I am doing wrong here ?

P.S. I don't want to change the fact that I pass a logger object directly to each of these modules. Please help me without any changes to this.

Thanks!!

Upvotes: 1

Views: 321

Answers (2)

David K. Hess
David K. Hess

Reputation: 17246

logger.getLogger() returns the same root logger object each time it is called and therefore you are modifying the same logger. I.e. a setLevel() call anywhere will change the root logger behavior everywhere.

Instead, for the other set of modules use logger.getLogger("mymodules"). This will return a new logger instance. Calling setLevel() on this logger will not affect the root logger.

From the docs:

The name is potentially a period-separated hierarchical value, like foo.bar.baz (though it could also be just plain foo, for example). Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of foo, loggers with names of foo.bar, foo.bar.baz, and foo.bam are all descendants of foo. The logger name hierarchy is analogous to the Python package hierarchy, and identical to it if you organise your loggers on a per-module basis using the recommended construction logging.getLogger(name). That’s because in a module, name is the module’s name in the Python package namespace.

Upvotes: 1

PepperoniPizza
PepperoniPizza

Reputation: 9102

First of all, logging instances on python are singleton, which means if you call getLogger() anywhere on your code you are getting the same one logger instance

I would create as many instances as different kind of loggers that you need, that way you don't need to pass them to soubmodules, you can just call them with their name. You have to give them a name first:

logger = logging.getLogger('logger_with_error')

Since logger is a singleton, I don't think is a good idea to be constantly swithing the logger type in excecution, that can lead to problems.

Upvotes: 1

Related Questions