Quick start logging. Here are some short examples of logging in Python 2.7.
Basic logging to file
import logging # change default log entry format, set filename and logging level logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s", filename="example.log") logging.info("Started") logging.info("This is an example entry") logging.debug("This line won't get logged as the log level is INFO") logging.info("Done.") # perform an orderly shutdown by flushing and closing all handlers; called at application exit and no further use of the logging system should be made after this call. logging.shutdown()
Slightly less basic
Logging to file and console
import logging import logging.handlers # log file name and logging message level log_file_name = 'loggingexample.log' log_level = logging.INFO # log record format string format_string = '%(asctime)s %(name)s %(levelname)s %(message)s' # set default logging (to console) logging.basicConfig(level=log_level, format=format_string) # set logging to file log_formatter = logging.Formatter(format_string) file_handler = logging.FileHandler(log_file_name, mode='w') # mode is file write mode, 'a' to append file_handler.setFormatter(log_formatter) # create child logger and set it to be a file handler logger = logging.getLogger() # or pass a string to give it a name logger.addHandler(file_handler) logger.setLevel(log_level) # log some messages logger.info("Started") logger.info("This is an example entry") logger.debug("This line won't get logged as the log level is INFO") logger.info("Done.") # perform an orderly shutdown by flushing and closing all handlers; called at application exit and no further use of the logging system should be made after this call. logging.shutdown()
TimedRotatingFileHandler
Official docs: http://docs.python.org/library/logging.handlers.html#timedrotatingfilehandler
This log handler is really useful for regularly scheduled scripts as the logs get rotated rather than filing all available space given enough time.
#!/usr/bin/env python #------------------------------------------------------------------------------- # Name: example-TimedRotatingFileHandler.py # Purpose: Write log using TimedRotatingFileHandler # Author: Adrian Jones # Created: 2012-05-25 # # TimedRotatingFileHandler: from handler.py source: # Current 'when' events supported: # S - Seconds # M - Minutes # H - Hours # D - Days # midnight - roll over at midnight # W{0-6} - roll over on a certain day; 0 - Monday # # Case of the 'when' specifier is not important; lower or upper case # will work. # # Interval is in seconds # backupCount in number of old log files to keep # #------------------------------------------------------------------------------- import time import logging import logging.handlers log_file_name = 'TimedRotatingFileHandler.log' logging_level = logging.DEBUG try: # set TimedRotatingFileHandler for root formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s') # use very short interval for this example, typical 'when' would be 'midnight' and no explicit interval handler = logging.handlers.TimedRotatingFileHandler(log_file_name, when="S", interval=30, backupCount=10) handler.setFormatter(formatter) logger = logging.getLogger() # or pass string to give it a name logger.addHandler(handler) logger.setLevel(logging_level) # generate lots of example messages for i in range(10000): time.sleep(0.1) logger.debug('i=%d' % i) logger.info('i=%d' % i) logger.warn('i=%d' % i) logger.error('i=%d' % i) logger.critical('i=%d' % i) except KeyboardInterrupt: # handle Ctrl-C logging.warn("Cancelled by user") except Exception as ex: # handle unexpected script errors logging.exception("Unhandled error\n{}".format(ex)) raise finally: # perform an orderly shutdown by flushing and closing all handlers; called at application exit and no further use of the logging system should be made after this call. logging.shutdown()
Steve Hammond
Many thanks for putting this out here! After many hours of googling to get rotating logs to work, I ran across this blog and your code snippet was the best thing that happened all day!!
Ade Jones
No problem Steve.
I must get around to posting the Py3k version.