settings.py. The code looked something like this:
This configuration worked out well in development. However I maintain a separate settings file for production,
Production.pymerely imports everything from
settings.pyand selectively overrides some of the attributes (set
DEBUG = False, for instance).
My problem was that I wanted the production logs to be written to a different location and perhaps even use a different handler. I could not think of a good way to do this without calling the logging code fragment again in
production.py. I wrote a utility function to do this (
configure_logging(filename)). This reduced code repetition but revealed another problem. When
production.pyimports everything from
settings.pyit triggers logging to be configured once using the
LOG_FILENAMEattribute used in development and then *again* using the
LOG_FILENAMEattribute used in production.
This was ugly. For one there is no need to configure logging twice; for another the initial configuration throws an error if the path described by
LOG_FILENAMEin development is not present in the production machine.
I wasn't sure how to proceed and I posed this question at Stack Overflow. I got an answer suggesting to switch
LOG_FILENAMEbased on the
DEBUGattribute. Something like this:
This looked good, but almost immediately revealed a problem.
DEBUGis overridden *inside*
production.pywhereas this code snippet is inside
settings.py. Consequently when the above given snippet gets executed
LOG_FILENAMEwill be pointed at the development environment.
I eventually found a solution from an answer to a different question. User Bluebird75 suggested using the 'module singleton' pattern to ensure that logging is only configured once. I extended his(?) suggestion to come up with the following solution:
The singleton module ensures that logging is only configured once. As this module resides within the app directory Django would already have loaded settings before this module is loaded, thereby ensuring the presence of
settings.LOG_FILENAME. I can add as many settings files as I want and all I have to do is override the
LOG_FILENAMEattribute in each file.