How to save the logs with TimedRotatingFileHandler at the specific hour?
Answer
To save logs with TimedRotatingFileHandler
in Python at a specific hour (e.g., every midnight or at a custom time), you can use the TimedRotatingFileHandler
and set the interval to 1
with the when='H'
parameter. You can then specify the time of day to start the rotation by adjusting the atTime
parameter.
Key Points:
when='H'
: This specifies that the rotation happens on an hourly basis.interval=1
: This defines the rotation happens once every hour (but you can adjust this if you need a different interval).atTime
: You can set this to the specific time you want the log to rotate. For instance, if you want the rotation to happen every midnight, you would set this todatetime.time(0, 0)
.
Here’s an example:
Example: Rotate Logs at Specific Hour (e.g., Midnight)
In this example, we set the log rotation to occur every day at midnight.
import logging
from logging.handlers import TimedRotatingFileHandler
import datetime
# Create a logger
logger = logging.getLogger('my_logger')
logger.setLevel(logging.DEBUG)
# Set the specific time when you want the log to rotate (midnight in this case)
rotation_time = datetime.time(0, 0) # Rotate at midnight
# Set up the TimedRotatingFileHandler
handler = TimedRotatingFileHandler(
'my_log.log',
when='midnight', # Rotate at midnight
interval=1, # Rotate once a day
backupCount=7, # Keep the last 7 log files
atTime=rotation_time # Specify the exact time (midnight)
)
# Create a formatter and set it for the handler
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# Add the handler to the logger
logger.addHandler(handler)
# Sample logging messages
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
Explanation:
when='midnight'
: This specifies that the log should rotate at midnight.interval=1
: This indicates that the rotation should occur once per day.backupCount=7
: This keeps the last 7 log files (you can adjust this number based on your requirements).atTime=rotation_time
: This specifies that the log rotation should happen exactly at the specified time (rotation_time
).
Custom Hour Rotation:
If you want to rotate the log at a custom hour (e.g., 3 PM), you can change the rotation_time
to a datetime.time
object representing that time:
rotation_time = datetime.time(15, 0) # Rotate at 3:00 PM
This will rotate the logs every day at 3 PM.
Notes:
- Ensure that the time zone of your machine or application matches your expectations if you're working across time zones.
TimedRotatingFileHandler
rotates based on the system time, so be careful if your system time changes (e.g., during daylight savings time changes).