개발로그
[Python] Logging
pizzalist
2024. 4. 15. 21:36
Python Logging에 대한 설명과 방법
Python은 logging이라는 내장 라이브러리를 제공하여, 프로그램의 실행 중에 발생하는 이벤트를 기록하고 추적할 수 있습니다. 이를 통해 프로그램의 디버깅 및 유지보수를 용이하게 할 수 있습니다.
Logging 레벨(Levels)
Python logging은 다음과 같은 다섯 가지 레벨을 제공합니다.
- DEBUG: 디버깅 정보
- INFO: 정보성 메시지
- WARNING: 경고 메시지
- ERROR: 에러 메시지
- CRITICAL: 치명적인 에러 메시지
Logging 방법(Methods)
Python logging의 기본적인 사용 방법은 다음과 같습니다.
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')
위 코드에서는 logging 모듈을 import한 후, 기본 로그 레벨을 DEBUG로 설정합니다. 그리고 logger 객체를 생성한 후, 해당 객체의 메소드를 통해 각각의 로그 레벨에 맞는 메시지를 출력합니다.
하지만, 이외에도 logging 모듈은 다양한 기능을 제공합니다. 예를 들어, 로그를 파일로 저장하는 방법과 로그 포맷을 변경하는 방법 등이 있습니다.
Logging 파일 저장
로그를 파일로 저장하는 방법은 다음과 같이 구현할 수 있습니다.
import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.debug('This is a debug message')
logger.info('This is an info message')
위 코드에서는 logging.basicConfig() 메소드의 filename 인자를 통해 로그를 저장할 파일명을 지정합니다.
Logging 포맷 변경
로그의 출력 포맷을 변경하는 방법은 다음과 같이 구현할 수 있습니다.
import logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.DEBUG
)
logger = logging.getLogger(__name__)
logger.debug('This is a debug message')
logger.info('This is an info message')
위 코드에서는 logging.basicConfig() 메소드의 format 인자를 통해 로그의 출력 포맷을 변경합니다.
Python logging의 다양한 기능들을 학습하면서, 더욱 효율적인 로깅을 구현할 수 있게 될 것입니다.
- 쉘(shell)을 통한 Logging 내용 저장하기 관련 글