시행착오/[python]

[python] logging Module - 파이썬 로그 남기기 시행착오 정리

bled 2021. 3. 23. 14:07

파이썬으로 간단한 서버를 만들면서 로그를 남길필요가 있어 logging 모듈로 씨름하다 알게된 것 간단히 정리

logging 모듈로 할 수 있는 것

  • 원하는 시간단위로 로그파일 나눌 수 있음 => when = 'midnight' 로 하면 자정에 한번씩 나눠짐
  • 로그 파일 자동 압축 가능
  • 남기는 로그를 특정 형태로 포매팅 가능

코드는 다음과 같다

import gzip
import os
import logging.handlers

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

# 현재 파일 경로
current_dir = os.path.dirname(os.path.realpath(__file__))
# 로그 저장할 폴더 logs 생성
log_dir = '{}/logs'.format(current_dir)
if not os.path.exists(log_dir):
    os.makedirs(log_dir)

myLogger = logging.getLogger('test_log')
myLogger.setLevel(logging.DEBUG)  # 로깅 수준 지정


file_handler = logging.handlers.TimedRotatingFileHandler(
    filename='./logs/test', when='midnight', interval=1, encoding='utf-8'
)
file_handler.suffix = '%Y-%m-%d'  # 파일명 끝에 붙여줌; ex. log-20190811

myLogger.addHandler(file_handler)

formatter = logging.Formatter(
    '%(asctime)s|%(levelname)s|%(filename)s|%(funcName)s()|line:%(lineno)d|%(message)s'
    # '%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] %(message)s'
)
file_handler.setFormatter(formatter) # 포매팅
file_handler.rotator = GZipRotator() # 압축

myLogger.debug(msg='debug디버그')
myLogger.info('info인포')
myLogger.warning('warn워닝')
myLogger.error('error에러')

try:
    raise Exception('예외')
except Exception as e:
    myLogger.exception(e)

 

참고

yurimkoo.github.io/python/2019/08/11/logging.html

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