logging – Python multiple logger for multiple modules

logging – Python multiple logger for multiple modules

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.

import logging

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

def module1():
    general_logger.info(Logger Module1)
    url_info_logger.info(New URL found)

def do_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.

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


import logging

class MyClassName:

    def __init__(self, general_logger, url_info_logger):
    self.general_logger = general_logger
    self.url_info_logger = url_info_logger

    def module1(self):
    self.general_logger.info(Logger Module1)
    self.url_info_logger.info(New URL found)

    def do_something(self):
    self.general_logger.info(Logger Module2)
    self.url_info_logger.info(Url parsed)

In the main

myobj = MyClassName(general_logger,url_info_logger)

logging – Python multiple logger for multiple modules

Leave a Reply

Your email address will not be published. Required fields are marked *