Wednesday 23 December 2015

Python: logging to a file

Most of the time, we used to log messages to a file. In this post, I am going to explain how to log messages to a file.

logging.basicConfig(filename='/Users/harikrishna_gurram/temp.log',level=logging.DEBUG)

Above statement logs messages to ‘/Users/harikrishna_gurram/temp.log’ file.
import logging

logger = logging.getLogger()
logging.basicConfig(filename='/Users/harikrishna_gurram/temp.log',level=logging.DEBUG)

def logMessages():
    logger.debug("Debug message")
    logger.info("Information Message")
    logger.warn("Warning Message")
    logger.error("Error Message")
    logger.critical("Critical Message")

if (__name__ == "__main__"):
    logMessages()


Run above program, all the log messages are logged to temp.log file.
$ cat temp.log
DEBUG:root:Debug message
INFO:root:Information Message
WARNING:root:Warning Message
ERROR:root:Error Message
CRITICAL:root:Critical Message


Previous                                                 Next                                                 Home

No comments:

Post a Comment