Skip to content Skip to sidebar Skip to footer

Python Multiple Logger For Multiple Modules

I have two files namley main.py and my_modules.py. In main.py I have defined two loggers like this #main.py URL_LOGS = 'logs/urls.log' GEN_LOGS = 'logs/scrape.log'

Solution 1:

Quote from logging documentation: Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.

So what you want to do in your my_modules.py is just to call the getLogger() again with the same name.

#my_modules.py   
import logging

url_info_logger = logging.getLogger('URL_Fetcher')
general_logger = logging.getLogger("GENERAL")

defmodule1():
    general_logger.info("Logger Module1")
    url_info_logger.info("New URL found")

defdo_something():
    general_logger.info("Logger Module2")
    url_info_logger.info("Url parsed")    

It should return the same logging object, since it is already defined before you call it the second time.

Solution 2:

if you transform the second module in a class, you can simply:

  • declare the logger in the first modulue
  • create the new class passing the 2 logger as parameters
  • use the logger in the new class

Example:

import logging

classMyClassName:

    def__init__(self, general_logger, url_info_logger):
    self.general_logger = general_logger
    self.url_info_logger = url_info_logger

    defmodule1(self):
    self.general_logger.info("Logger Module1")
    self.url_info_logger.info("New URL found")

    defdo_something(self):
    self.general_logger.info("Logger Module2")
    self.url_info_logger.info("Url parsed")

In the main

#main.py
...
myobj = MyClassName(general_logger,url_info_logger)
myobj.do_something()
myobj.module1()

Post a Comment for "Python Multiple Logger For Multiple Modules"