I am trying to add a module to a project that uses the standard Python (2.7) logging libraries. What I want to achieve is the following:
- Anything equal or worse than WARNING goes to wherever the main program (outside of my control) has configured the logging to go (usually stderr)
- Everything else (debug messages mainly) goes to a log file
Please note that the key issue here is that I do not want to modify the global logging settings, since those are controlled by the main app. Otherwise I would use the example in here:
http://docs.python.org/2/howto/logging-cookbook.html#logging-to-multiple-destinations
I’ve tried this:
logger = logging.getLogger('my_module')
logger.setLevel(logging.WARNING)
fh = logging.FileHandler('my_module.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
but then I only get warning messages in my file.
If I replace the above line with:
logger.setLevel(logging.DEBUG)
then I get debug messages in both stderr and my file.
Then I tried this:
logger = logging.getLogger('my_module')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.NullHandler())
console = logging.StreamHandler()
console.setLevel(logging.WARNING)
logger.addHandler(console)
fh = logging.FileHandler('my_module.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
But again no luck.
So can I achieve this without having to call basicConfig() or anything else that affects the global logging infrastructure? I only want to modify my own module here if possible.
Thanks!
You can’t do it with a single logger without setting WARNING level on ancestor’s handlers. From the docs:
In general other than the setting of WARNING level for the logger and adding
NullHandler(), library code shouldn’t configure logging at all.If you want an easy way for the main application to provide you with a debug info then define a function that configures DEBUG level logging for your library.
If you can’t control the main program then you shouldn’t create debug files as a side-effect of using your_module unless explicitly asked to do so:
''is a root logger.'a.b'is a child of'a'logger.