I have written a code that would rotate logs on midnight maintaing backup of 1 day. But the next day, the previous logs are getting deleted.
For example :
While I am checking logs on 14th Feb, I noticed that all the logs generated on 13th Feb, got deleted from instancelogs.log.2025-02-13. The first log generated on 14th Feb is getting stored in instancelogs.log.2025-02-13 file instead of instancelogs.log file , the remaining logs for 14th Feb are correctly stored in instancelogs.log file.
Please look into the issue as we are losing all the logs for 13th of Feb.
It sounds like there are multiple rollover events occurring. The first rollover correctly moves instancelogs.log to instancelogs.log.<date> and creates a new instancelogs.log. Then a second rollover occurs, again moving the (mostly empty) instancelogs.log to instancelogs.log.<date>, overwriting the backup file.
I haven’t been able to reproduce this, but I imagine it could happen if your logging code is run in multiple concurrent instances.
I haven’t been able to reproduce the issue, even with the exact example script you provided.
A few things you could try:
Decrease the log rotation time. Does the issue still occur with rotation times of an hour, or even a minute?
Change the rollover time. Instead of rolling over at midnight, you can use the atTime parameter to set the rollover to e.g. 3 AM.
Override the default BaseRotatorHandler.rotator attribute to something which keeps track of the exact times it is called. This could verify whether the rollover really does happen multiple times, as I suspect.
I have already tried decreasing log rotation time. The issue doesnot occur with 2 minutes or 10 minutes set as rotation time.
Have changed the rollover time this time.
I have seen another issue, when today(on 17th Feb), yesterday’s logfile (16th Feb’s log file) is getting backedup with the name of 15th Feb (instancelogs.log.2025-02-15), where my backupcount is set to 1. This instancelogs.log.2025-02-15 file has got logs of 16th Feb and is present today on 17th feb
Hi @abessman
I believe you were correct, there are multiple concurrent instances. So sorry I missed this information.
I am running a script that imports the above logger script, using :
gunicorn --timeout 6000 -w 2 -k uvicorn.workers.UvicornWorker …
This workers are initializing the TimedRotationHandler twice handlers twice.
Is this the cause of the issue I am facing?
Can you suggest a fix for this?
Use QueueHandler to write log messages to a multiprocessing.Queue from these workers, then use a single separate process to pass this queue to your TimedRotatingFileHandler.