Here’s a simple logging example that just logs to a file. In order, it creates a Logger instance, then a FileHandler and a Formatter. It attaches the Formatter to the FileHandler, then the FileHandler to the Logger. Finally, it sets a debug level for the logger.
import logging logger = logging.getLogger('myapp') hdlr = logging.FileHandler('/var/tmp/myapp.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.WARNING)
We can use this logger object now to write entries to the log file:
logger.error('We have a problem') logger.info('While this is just chatty')
If we look in the file that was created, we’ll see something like this:
2003-07-08 16:49:45,896 ERROR We have a problem
The info message was not written to the file – we called the setLevel method to say we only wanted
WARNING or worse, so the info message is discarded.
The timestamp is of the form « year-month-day hour:minutes:seconds,milliseconds. » Note that despite the three digits of precision in the milliseconds field, not all systems provide time with this much precision.