2

I am using logging module in python. In my main.py file I am using two logger.

  1. Root logger (To get logs from multiple modules in same directory)
  2. Local logger (To log specific information)

I want information of local logger to be separate from root logger. But when I am creating separate logger. Information of local logger is also present in root logger info.

Here is the sample of how I am doing this

# main.py
import logging

def setup_logger(filename, name = ''):
    if name == '':
        logging.basicConfig(filename=filename,
                            format='%(asctime)s %(funcName)s %(levelname)s %(message)s',
                            filemode='a')
        logger = logging.getLogger()
    else:
        """
        handler = logging.FileHandler(filename, mode = 'a')
        handler.setFormatter(logging.Formatter('%(asctime)s %(funcName)s %(levelname)s %(message)s'))
        logger = logging.getLogger(name)
        logger.addHandler(handler)
        """
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        handler = logging.FileHandler(filename)
        handler.setFormatter(formatter)

        logger = logging.getLogger(name)
        logger.setLevel(logging.DEBUG)
        logger.addHandler(handler)

        return logger
    logger.setLevel(logging.DEBUG)
    return logger

logger = setup_logger('main.log')
local_logger = setup_logger('local_log.log', 'local_log')
# other file under root log
logger = logging.getLogger("__main__." + __name__)
2
  • Have you looked at the logger hierarchy, and how your loggers relate to the root logger? Commented Jan 10, 2021 at 6:53
  • yeah, I want local_logger to be independent of log hierarchy. But somehow it is relating to root_logger. I am not sure how to differentiate those two. Commented Jan 10, 2021 at 8:15

1 Answer 1

5

You have to stop propagation if you don't want the local loggers to send their logs to the root loggers handlers:

logger.propagate = False

This part of the documentation explains it well: https://docs.python.org/3/howto/logging.html#logging-flow

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.