Can anyone suggest a way in python to do logging with:
- log rotation every day
- compression of logs when they’re rotated
- optional – delete oldest log file to preserve X MB of free space
- optional – sftp log files to server
Thanks for any responses,
Fred
encoding='bz2'parameter. (Note this “trick” will only work for Python2. ‘bz2’ is no longer considered an encoding in Python3.)You could (indirectly) arrange this using a RotatingFileHandler. By setting the
maxBytesparameter, the log file will rollover when it reaches a certain size. By setting thebackupCountparameter, you can control how many rollovers are kept. The two parameters together allow you to control the maximum space consumed by the log files. You could probably subclass theTimeRotatingFileHandlerto incorporate this behavior into it as well.Just for fun, here is how you could subclass
TimeRotatingFileHandler. When you run the script below, it will write log files to/tmp/log_rotate*.With a small value for
time.sleep(such as 0.1), the log files fill up quickly, reach the maxBytes limit, and are then rolled over.With a large
time.sleep(such as 1.0), the log files fill up slowly, the maxBytes limit is not reached, but they roll over anyway when the timed interval (of 10 seconds) is reached.All the code below comes from logging/handlers.py. I simply meshed TimeRotatingFileHandler with RotatingFileHandler in the most straight-forward way possible.