JS.
JS.

Reputation: 16097

"Linking" or forwarding sub-loggers in Python

I've been following (what I believe) is the correct practice WRT to logging when creating library functions. I do the following to create a sub-logger within a given function of my library:

my_lib.py

import logging
def my_func():
    log = logging.getLogger('my_lib.my_func')
    log.debug("You've just called my_lib.my_func!")

In my main program, I get a logger "for free" from the project's library. This Project logger has handlers and formatters already set up. The output format is fancy and is the preferred way to log for this project.

By default, my_lib's loggers inherit the logging level (logging.INFO) of the main (logging.getLogger('')) logger , therefore the log.debug() message isn't seen by default when the program is run.

If I want to see the logging message from my library, I can configure the my_lib.my_func logger like so from my main program:

logging.getLogger("my_lib.my_func").level = logging.DEBUG

This works, however the messages aren't formatted as they would be if they had been handled by the Project logger.

In the main program, is there a way to "link" or forward logging messages from the my_lib.my_func logger to the Project logger to take advantage of the formatting provided by the Project logger?

Upvotes: 5

Views: 1927

Answers (1)

Vinay Sajip
Vinay Sajip

Reputation: 99365

If you set the handlers/formatters which are currently added to the project logger to the root logger, then you will get all logging using them, including the logging from my_Lib.my_func. Otherwise, you will have to duplicate the same set up as the project logger has for the my_lib logger (or the my_lib.my_func logger).

Upvotes: 4

Related Questions