python logging timezone 변경 하기

시스템 시간은 UST인데 Python 프로그램에서만 timezone을 변경하여 log를 출력할 일이 있습니다. 시스템 시간 변경 시 영향을 주는 곳이 많기 때문에 특정 프로그램 사용에만 timezone 변경하려는 의도였는데요.

간단하게 바꾸는 방법은 찾지 못하고 아래와 같이 logging Formatter를 수정하는 방법이 있어 포스팅 해봅니다.

import pytz
import logging
import datetime


class Formatter(logging.Formatter):
    """override logging.Formatter to use an aware datetime object"""

    def converter(self, timestamp):
        # Create datetime in UTC
        dt = datetime.datetime.fromtimestamp(timestamp, tz=pytz.UTC)
        # Change datetime's timezone
        return dt.astimezone(pytz.timezone('America/Denver'))

    def formatTime(self, record, datefmt=None):
        dt = self.converter(record.created)
        if datefmt:
            s = dt.strftime(datefmt)
        else:
            try:
                s = dt.isoformat(timespec='milliseconds')
            except TypeError:
                s = dt.isoformat()
        return s


console = logging.FileHandler('UpdateSubsStatus.log')
console.setFormatter(Formatter(
    '%(asctime)s;%(name)s - %(levelname)s - %(message)s', '%Y-%m-%d %H:%M:%S'))
logging.getLogger('').addHandler(console)
logging.critical("Critical event")

위와 같은 형태인데요. logging.Formatter를 override 해서 시간을 변경하는 방법입니다.

참고

  • https://stackoverflow.com/questions/67207677/logging-in-python-with-correct-timezone

Leave a Reply