클래스에서 어떤 방법으로 로깅을 구현할 수 있나요?

Python에서는 logging이라는 내장 모듈을 사용하여 로깅을 구현할 수 있습니다. 아래는 logging 모듈을 사용하여 클래스에서 로깅을 구현하는 예제입니다.

import logging

class MyClass:
    def __init__(self, name):
        self.name = name
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)
        self.file_handler = logging.FileHandler('logfile.log')
        self.file_handler.setLevel(logging.DEBUG)
        self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.file_handler.setFormatter(self.formatter)
        self.logger.addHandler(self.file_handler)

    def do_something(self):
        self.logger.debug('Debug message')
        self.logger.info('Info message')
        self.logger.warning('Warning message')
        self.logger.error('Error message')
        self.logger.critical('Critical message')

위 예제에서는 logging.getLogger() 함수를 사용하여 로거 객체를 생성합니다. 로거 객체를 생성할 때 클래스의 이름을 로거의 이름으로 지정하여 로깅 메시지의 출처를 확인할 수 있습니다. 로깅 수준은 setLevel() 메서드를 사용하여 설정하며, 로그 파일은 FileHandler를 사용하여 관리합니다. 로그 메시지의 형식은 Formatter를 사용하여 설정할 수 있습니다.

클래스의 메서드에서는 생성한 로거 객체를 사용하여 로깅 메시지를 출력할 수 있습니다. debug(), info(), warning(), error(), critical() 메서드를 사용하여 로깅 수준에 맞춰 메시지를 출력합니다.

자세한 내용은 Python의 공식 문서(https://docs.python.org/3/library/logging.html)를 참조하시기 바랍니다.

#Python #로깅