Monday, 28 December 2015

Python: RotatingFileHandler: Rotate log files

RotatingFileHandler is used to rotate log files.

Syntax
logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)

Argument
Description
filename
Full path of the file name.
mode
By default file open in append mode. You can specify the mode.
maxBytes
When the file size about to reach maxBytes, the file is closed and a new file is silently opened for output.
backupCount
If backupCount is non-zero, the system will save old log files by appending the extensions ‘.1’, ‘.2’ etc., If backupCount is 3 and file name is temp.log, then, when this file is filled, it is closed and renamed to temp.log.1, temp.log.2, temp.log.3.
encoding
File opened with given encoding
delay
If delay is true, then file opening is deferred until the first call to emit().

Following are the methods provided by RotatingFileHandler class.
Method
Description
doRollover()¶
Does rollover.
emit(record)
Write record to a file.

Note:
If either of maxBytes or backupCount is zero, rollover never occurs.
import logging
import glob
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.RotatingFileHandler(LOG_FILENAME, maxBytes=1000, backupCount=10)

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

#Adding handler to logger
logger.addHandler(handler)
logger.propagate = False

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__"):
    for i in range(1000):
        logMessages()

    # See what files are created
    logfiles = glob.glob('%s*' % LOG_FILENAME)

    for filename in logfiles:
        print(filename)


Run above program, you will get following output.
/Users/harikrishna_gurram/temp.log
/Users/harikrishna_gurram/temp.log.1
/Users/harikrishna_gurram/temp.log.10
/Users/harikrishna_gurram/temp.log.2
/Users/harikrishna_gurram/temp.log.3
/Users/harikrishna_gurram/temp.log.4
/Users/harikrishna_gurram/temp.log.5
/Users/harikrishna_gurram/temp.log.6
/Users/harikrishna_gurram/temp.log.7
/Users/harikrishna_gurram/temp.log.8
/Users/harikrishna_gurram/temp.log.9


Above program creates 10 log files using rotation.



Previous                                                 Next                                                 Home

No comments:

Post a Comment