Saturday 26 December 2015

Python: File Handler

By using File handler, we can send log messages to a file.

Syntax
logging.FileHandler(filename, mode='a', encoding=None, delay=False)

Argument
Description
filename
Full path of the file
mode
File is opened in this mode. If you don’t specify any mode, file is open in append mode by default.
encoding
Opens file with given encoding.
delay
If delay is true, then file opening is deferred until the first call to emit(). Default value is False.

File handler provides following methods.
Method
Description
close()
Closes the file
emit(record)
Output the record to file


import logging
import sys

#Define logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

#Define handler to write to standard output
handler = logging.FileHandler("/Users/harikrishna_gurram/temp.log", encoding="UTF-8")
formatter = logging.Formatter('[%(levelname)s] %(message)s')
handler.setFormatter(formatter)
handler.setLevel(logging.WARN)

#Adding handler to logger
logger.addHandler(handler)

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()
    handler.close()


Run above program, you will get following output in console.
2015-10-23 10:32:33,264 __main__     DEBUG    Debug message
2015-10-23 10:32:33,264 __main__     INFO     Information Message
2015-10-23 10:32:33,264 __main__     WARNING  Warning Message
2015-10-23 10:32:33,264 __main__     ERROR    Error Message
2015-10-23 10:32:33,264 __main__     CRITICAL Critical Message


Following log messages are logged to temp.log.
$ cat temp.log
[WARNING] Warning Message
[ERROR] Error Message
[CRITICAL] Critical Message







Previous                                                 Next                                                 Home

No comments:

Post a Comment