It is used
to rotate log files at certain timed intervals.
Syntax
logging.handlers.TimedRotatingFileHandler(filename,
when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False,
atTime=None)
Argument
|
Description
|
filename
|
Full path
of file name.
|
when
|
Specifies
the type of interval in hours, minutes, seconds etc.
|
interval
|
Specifies
interval.
|
backupCount
|
Number of
files to take backup. If more would be created when rollover occurs, the
oldest one is deleted.
|
encoding
|
File
opened with given encoding
|
delay
|
If delay
is true, then file opening is deferred until the first call to emit().
|
utc
|
If the utc
argument is true, times in UTC will be used; otherwise local time is used.
|
atTime
|
If atTime
is not None, it must be a datetime.time instance which specifies the time of
day when rollover occurs.
|
You can
specify following values to the argument ‘when’.
Value
|
Type of interval
|
‘S’
|
Seconds
|
‘M’
|
Minutes
|
‘H’
|
HoursDays
|
‘D’
|
Days
|
‘W0’-‘W6’
|
W0
represents Monday, W1 represents Tuesday etc.
|
‘midnight’
|
Roll over
at midnight
|
import logging import logging.handlers import time #Define logger logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s') LOG_FILENAME="temp.log" #Define handler to write to standard output handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when='M', interval=1) formatter = logging.Formatter('[%(levelname)s] %(message)s') handler.setFormatter(formatter) handler.setLevel(logging.DEBUG) #Adding handler to logger logger.addHandler(handler) logger.setLevel(logging.DEBUG) def logMessages(): time.sleep(60) 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(5): logMessages()
Run above program,
it creates 6 files temp.log and other five files are like
temp.log.%Y-%m-%d_%H-%M-%S format.
No comments:
Post a Comment