Python, want logging with log rotation and compression

后端 未结 9 1161
暖寄归人
暖寄归人 2020-11-28 01:43

Can anyone suggest a way in python to do logging with:

  • log rotation every day
  • compression of logs when they\'re rotated
  • optional - delete old
9条回答
  •  长情又很酷
    2020-11-28 02:37

    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:

    import gzip
    import logging
    import os
    from shutil import copy2
    from time import time
    
    def logRoll(logfile_name):
        log_backup_name = logfile_name + '.' + str(int(time()))
        try:
            copy2(logfile_name, log_backup_name)   
        except IOError, err:
            logging.debug(' No logfile to roll')
            return
        f_in = open(log_backup_name, 'rb')
        f_out = gzip.open(log_backup_name + '.gz', 'wb')
        f_out.writelines(f_in)
        f_out.close()
        f_in.close()
        os.remove(log_backup_name)
        f=open(logfile_name, 'w')
        f.close()
    

提交回复
热议问题