Tuesday, 29 December 2015

Python: WatchedFileHandler


WatchedFileHandler watches the file it is logging to. If file changed in-between logging, it closes the stream and reopens using the file name. This handler is used in UNIX/Linux environment. This handler is not appropriate for use under Windows, because under Windows open log files cannot be moved or renamed - logging opens the files with exclusive locks - and so there is no need for such a handler.
import logging
import logging.handlers

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

LOG_FILENAME="/Users/harikrishna_gurram/temp.log"
#Define handler to write to standard output
handler = logging.handlers.WatchedFileHandler(LOG_FILENAME)

formatter = logging.Formatter('[%(levelname)s] %(message)s')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)

#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()



Previous                                                 Next                                                 Home

No comments:

Post a Comment