Limiting the log file size in python, as far as I can tell, can be done with the RotatingFileHandler and it's attribute maxBytes.
To test this, I wrote the following script:
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger("Rotating Log")
logger.setLevel(logging.INFO)
# add a rotating handler
handler = RotatingFileHandler("test.log", maxBytes=1)
logger.addHandler(handler)
x = 0
while True:
x += 1
logger.info(x)
Even though the logfile should not exceed 1 byte, it goes up until many megabytes pretty quickly. How can I limit this? Sadly the documentation is pretty bad. I also wanted to know how to make sure that every time I rerun the python script, the log file is cleared and started fresh, however, in the docu it just says
class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False)
If mode is not specified, 'a' is used.
However, it does not say what other options instead of 'a' there are.
To sum up the questions
- How can I limit the log file size to, let's say 10 megabytes
- How can I ensure a fresh logfile is started if the script is run, and not an old one appended
Edit: I tried it with maxBytes=1000000, but the result remained the same. The logfile just keeps getting bigger