[module] logging

반디·2023년 3월 7일
0

Python

목록 보기
8/11

logging

SW가 실행될 때 발생하는 이벤트를 추척하는 수단

구문수행 작업
logging.info(), logging.debug()정상 작동 중에 발생하는 이벤트 보고
warnings.warn(), logging.warning()특정 이벤트와 관련하여 경고 발행
logging.error(), logging.exception(), logging.critical()예외를 발생시키지 않고 에러의 억제(어떻게 에러가 처리되었는지)를 보고
  • CRITICAL > ERROR > WARNING > INFO > DEBUG 순으로 심각한 오류
Level사용 목적
DEBUG작동 상태를 진단하는 목적으로 자세한 출력이 필요한 경우
INFO정상적으로 작동되고 있는지를 확인
WARNING예상치 못한 상황이 발생하거나 향후 문제 발생이 예상되는 경우 (디스크 용량 부족 등)
ERROR오류로 인해 프로그램의 특정 기능이 실행되지 못하고 있는 경우
CRITICAL오류로 인해 프로그램 자체가 실행될 수 없는 경우
Example
  1. console에 로그 출력
import logging
logging.warning('warning!')  # console에 메시지를 출력 
logging.info('logging_info')  # console에는 메시지를 출력하지 않음 
  1. 파일에 로그 출력 및 저장
    - '시간 loglevel 메세지' 형식으로 출력되도록 지정
import logging
logging.basicConfig(filename='example.log', format='%(asctime)s %(levelname)s %(message)s', encoding='utf-8', level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
logging.error('And non-ASCII stuff, too, like Øresund and Malmö')
  1. logger class
import logging

logger = logging.getLogger(__name__) #Logger class를 선언
logger.warning('This is a warning') #call by reference

Note __name__ : 현재 module의 이름을 담고 있는 변수
해당 로그가 어느 module에서 발생한 메세지인지 확인할 수 있어야 하므로, getLogger로 logger object를 호출할 때 __name__ 이용을 권장

  1. using handlers
    - log message를 standard output stream이나 파일 등 원하는 곳으로 보내주는 역할
import logging

# Create a custom logger
logger = logging.getLogger(__name__) 

# Create handlers
c_handler = logging.StreamHandler()
c_handler.setLevel(logging.WARNING)

# Create formatters and add it to handlers
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
c_handler.setFormatter(c_format)

# Add handlers to the logger
logger.addHandler(c_handler)

logger.warning('This is a warning')
logger.error('This is an error')

참고문헌

profile
꾸준히!

0개의 댓글