5

I want to add a custom logger to a python application I am working on. I think that the logging module intends to support this kind of customization but I don't really see how it works with the typical way of using the logging module. Normally, you would create a logger object in a module like,

import logging
logger = logging.getLogger(__name__)

However, somewhere in the application, probably the entry-point, I will have to tell the logging module to use my logger class,

logging.setLoggerClass(MyLogger)

However, this is often going to be called after modules have been imported and the logger objects are already allocated. I can think of a couple of ways to work around this problem (using a manager class to register logger allocations or calling getLogger() for each log record -- yuk), but this does not feel right and I wanted to know what the right way of doing this is.

1 Answer 1

2

Any logging initialisation / settings / customisation should be done before the application code runs. You can do this by putting it in the __init__.py file of your main application directory (this means it'll run before any of your modules are imported / read).

You can also put it in a settings.py module and importing that module as the first thing in your application. As long as the logging setup code runs before any getLogger calls are made then you're good.

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

2 Comments

Argh. Typically, I have not actually used the __init__.py file for initialization, just for package structure and importing convenient functions. It seems pretty obvious that it is the right place for initialization code :) However, one of the logging handlers I want to add to the logger is a file handler so that has a log path that the user can specify from the command line. I guess I could add that as a class variable that can pass on changes to instances, but I am don't feel that's a great way of doing it because it creates a race condition.
After a little experimentation, I think I understand. Previously, I was installing the handlers as a part of the logger initialization, which I think is the wrong thing to do. I have move the handler addition into the entry-point code, which avoids any race condition on the file handler and ensures that modules using logging.getLogger() get the customized class as I wanted. Thanks for your help!

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.