Home > Software design >  Why are my logs going to multiple places?
Why are my logs going to multiple places?

Time:05-19

I am trying to split my logs into two files. I have the main log (root) and a child log called 'auxlog'. I have specified auxlog to log to its own file, which it does successfully, but it also appears in the root log. I don't know if I am misunderstanding the fundamentals of the logging module or if I just missed a config option. Basically, I want to split my logs into two categories as follows:

  • one log to handle the overall function of my application, and
  • another log that handles logging for one specific class.

Both of these are working but the log for the specific class is redundant as it is written to both files. Here is my code:

logging.basicConfig(filename='app.log', level=logging.INFO, format='[%(asctime)s][%(name)s][%(levelname)s]: %(message)s')

# Aux Logger
auxlog = logging.getLogger("auxlog")
aux_handler = logging.FileHandler("aux.log")
aux_handler.setFormatter(logging.Formatter("[%(asctime)s]:[%(name)s]\t%(message)s"))
auxlog.setLevel(logging.INFO)
auxlog.addHandler(aux_handler)

And when I use the auxlog in my special class, I just call auxlog.info("my message here") , however, it still appears in app.log

CodePudding user response:

TL;DR: You can achieve your desired behavior by setting auxlog.propagate = False.

Python loggers work by forming a tree based on logger names (split on '.'). The root logger, as the name suggests, forms the root of this tree. So for example, a logger named a.b would be a child of a, which would be a child of the root logger.

By default, all logs will propagate up to their parent loggers. Importantly, Handlers do not prevent this propagation behavior - i.e. they act like a "tee", not a "sink". You have to explicitly turn off propagation on specific logger(s) if you want them to be isolated.

  • Related