Python‎ > ‎

Easy Python Logging

posted Sep 4, 2014, 11:58 PM by Chris G
Sometimes it is useful to log the status of the execution of a program to a logfile for auditing, or for troubleshooting. The following code will enable you to do so. The logfile will also contain a date and timestamp in the format defined in the basicConfig statement.
import logging

logging.basicConfig(filename="logfile.log", level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

try:
    file = open("myfile.txt", 'r')
    TEXT = file.read()
    file.close
    logging.info("Read file OK")
except Exception, e:
    logging.error("Failed: to open logfile: " + str(e))


Comments