포스트

python 프로그램 커스텀 로깅 클래스 만들기(라이트 버전)

기본 로깅 관련 내용은 이전 포스팅을 참조해주세요.

https://blog.naver.com/devramyun/223749582224

[20250206] python 프로그램 로그 저장 파이썬 실행 중에 터미널에 출력되는 모든 로그(표준 출력 및 표준 오류)를 파일로 저장하는 간단한 방법이… 파이썬 실행 중에 터미널에 출력되는 모든 로그(표준 출력 및 표준 오류)를 파일로 저장하는 간단한 방법이…

더 자세한 커스텀 로깅 버전은 최신 포스팅을 참조해주세요. https://blog.naver.com/devramyun/223749702537

[20250206] python 프로그램 커스텀 로깅 클래스 만들기(디테일 버전) python 디폴트 로거 관련 포스팅은 다음을 참조해주세요. https://blog.naver.com/devramyun/223749582224 … python 디폴트 로거 관련 포스팅은 다음을 참조해주세요. https://blog.naver.com/devramyun/223749582224 …


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import logging
import sys
import os
from datetime import datetime

# 실행할 때마다 새로운 로그 파일 생성
log_dir = "logs"  # 로그 파일을 저장할 디렉토리
os.makedirs(log_dir, exist_ok=True)  # 디렉토리 생성 (없으면 자동 생성)

# 실행 시간 기반 로그 파일명 설정 (예: logs/log_2025-02-06_12-30-45.log)
log_filename = os.path.join(log_dir, f"log_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.log")

# 로거 설정
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
    handlers=[logging.FileHandler(log_filename, encoding="utf-8"), logging.StreamHandler(sys.stdout)],  # 실행마다 다른 파일 저장  # 터미널에도 출력
)


class SingletonMeta(type):
    """싱글톤 메타클래스"""

    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class MyLogger(metaclass=SingletonMeta):
    def __init__(self, name: str = "default"):
        self.logger = logging.getLogger(name)

    def info(self, message: str):
        self.logger.info(message)

    def error(self, message: str):
        self.logger.error(message)

    def exception(self, message: str):
        self.logger.exception(message)

    def warning(self, message: str):
        self.logger.warning(message)


# ✅ 싱글톤 로거 인스턴스 생성
myLogger = MyLogger()

위와 같이 클래스를 만들어주고,

아래와 같이 실행해주시면 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
if __name__ == "__main__":
    success = False
    try:
        ... 이전 프로그램 코드
        myLogger.info(f"process completed")
        success = True
    except KeyboardInterrupt:
        myLogger.warning("사용자가 실행을 중단했습니다 (Ctrl+C)")
    except Exception as e:
        myLogger.exception("예외 발생: %s", e)
    finally:
        myLogger.info("프로그램 종료, 성공: {}".format(success))

유용히 사용해주세요.

감사합니다.

sticker

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.