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
I guess it's too late to join the party, but here is what I did. I created a new class inheriting
logging.handlers.RotatingFileHandler
class and added a couple of lines to gzip the file before moving it.https://github.com/rkreddy46/python_code_reference/blob/master/compressed_log_rotator.py
Be warned: The class signatures have changed in python 3. Here is my working example for python 3.6
encoding='bz2'
parameter. (Note this "trick" will only work for Python2. 'bz2' is no longer considered an encoding in Python3.)maxBytes
parameter, the log file will rollover when it reaches a certain size. By setting thebackupCount
parameter, 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 theTimeRotatingFileHandler
to 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.
In addition to unutbu's answer: here's how to modify the TimedRotatingFileHandler to compress using zip files.
The other way to compress logfile during rotate (new in python 3.3) is using BaseRotatingHandler (and all inherited) class attribute rotator for example:
More you can see here.
To copy the file, gzip the copied file (using epoch time), and then clearing out the existing file in a way that won't upset the logging module: