Python logging greatly helps me to create transcripts of background processing scripts.
I have so far used the basic configuration:
import logging
LOG_FILENAME = 'example.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logging.debug('This message should go to the log file')
as explained in the Python docs: 15.6. logging. The nice thing of doing it this way is that you can use the line:
logging.debug('This message should go to the log file')
Throughout all your modules and classes without bothering with any of the logging configurations. Then you setup the logging in the main script to go to a file and all messages will go to that same file. Easy.
There is another way of doing the same, which goes something along these lines:
my_logger = logging.getLogger('MyLogger')
my_logger.setLevel(logging.DEBUG)
my_logger.debug('Test string')
Which is the same thing EXCEPT that you now have an instance to keep track of: my_logger. My modules and classes don't know how the logger of the day is named and having to pass another variable around would be cumbersome. I suspect I miss something very basic here, either my use of the logging module is faulty and only works thanks to some glitch or 2nd method must be very easy as well.
I want to switch to the 2nd method because that seems to be the only way to make use of additional features such as RotatingFileHandler.
From the documentation (https://docs.python.org/2/library/logging.html):
Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.
So you could get away without having to pass another variable around.
Furthermore, loggers form a hierarchy:
"loggers with names of foo.bar, foo.bar.baz, and foo.bam are all descendants of foo"
So the documentation recommends using:
logging.getLogger(__name__)
And in that way, organize the loggers in the same way you organize your modules.