[공부용]참고 사이트 모음/[python]

python logging with log rotation and compression - 파이썬 시간단위 자동 로그파일 분리 및 자동 압축

bled 2021. 3. 23. 11:04

stackoverflow.com/questions/8467978/python-want-logging-with-log-rotation-and-compression

 

Python, want logging with log rotation and compression

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 - s...

stackoverflow.com

import gzip
import os
import logging
import logging.handlers

class GZipRotator:
    def __call__(self, source, dest):
        os.rename(source, dest)
        f_in = open(dest, 'rb')
        f_out = gzip.open("%s.gz" % dest, 'wb')
        f_out.writelines(f_in)
        f_out.close()
        f_in.close()
        os.remove(dest)

logformatter = logging.Formatter('%(asctime)s;%(levelname)s;%(message)s')
log = logging.handlers.TimedRotatingFileHandler('debug.log', 'midnight', 1, backupCount=5)
log.setLevel(logging.DEBUG)
log.setFormatter(logformatter)
log.rotator = GZipRotator()

logger = logging.getLogger('main')
logger.addHandler(log)    
logger.setLevel(logging.DEBUG)

....