I am using windows 7 and python 2.7. I want to limit my log file size to 5MB. My app, when it starts, writes to log file, and then the app terminates. When my app starts again, it will write in same log file. So app is not continuously running. App initiates, processes and terminates.
My code for logging is:
import logging
import logging.handlers
logging.basicConfig(filename=logfile.log, level="info", format='%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
logging.info("*************************************************")
I tried with RotatingFileHandler but it didn't work
logging.handlers.RotatingFileHandler(logFile, mode='a', maxBytes=5*1024*1024, backupCount=2, encoding=None, delay=0)
So, how can I enforce a file size limit in python?
When you use logging.basicConfig with a file, the log is attached with a file handler to handle writing to the file. afterwards you created another file handler to the same file with logging.handlers.RotatingFileHandler
Now, once a rotate is needed, RotatingFileHandler is trying to remove the old file but it can't becuase there is an open file handler
this can be seen if you look directly at the log file handlers -
Lose
basicConfig()
and try this:This works on my machine