Python logging
포스트
취소

Python logging

로깅 예제 코드

  1. 코드

    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
    
    import logging
    from urllib.request import urlopen
    from urllib.error import HTTPError, URLError
    
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    FORMAT = "[%(levelname)s][ %(filename)s: %(funcName)s() ] %(message)s"
    logging.basicConfig(format=FORMAT, level=logging.INFO)
    
    
    def get_status_code(url):
        try:
            res = urlopen(url)
            return res.getcode()
        except HTTPError as e:
            logger.error(e)
        except URLError as e:
            logger.error(e)
        except Exception as e:
            logger.error(e)
        return
    
    
    if __name__ == '__main__':
        status_code = get_status_code('https://www.google.co.kr')
        logger.info(status_code)
    
        get_status_code('url??')
        get_status_code('https://www.wrong.url')
    
  2. 결과

    1
    2
    3
    
    [INFO][ logging_test.py: <module>() ] 200
    [ERROR][ logging_test.py: get_status_code() ] unknown url type: 'url??'
    [ERROR][ logging_test.py: get_status_code() ] <urlopen error [Errno 11001] getaddrinfo failed>
    

로깅 설정 상세사항은 파이썬 공식문서를 참고하자.

Fommter

이름포맷상세
asctime%(asctime)s날짜 시간, 밀리세컨드까지 출력
created%(created)f생성 시간 출력
filename%(filename)s파일명
funcnName%(funcName)s함수명
levelname%(levelname)s로그 레벨(DEBUG, INFO, WARNING, ERROR, CRITICAL)
levelno%(levelno)s로그 레벨을 수치화해서 출력(10, 20, 30, …)
lineno%(lineno)d소스의 라인 넘버
module%(module)s모듈 이름
msecs%(msecs)d로그 생성 시간에서 밀리세컨드 시간 부분만 출력
message%(message)s로그 메시지
name%(name)s로그 이름
pathname%(pathname)s소스 경로
process%(process)d프로세스(Process) ID
processName%(processName)s프로세스 이름
thread%(thread)dThread ID
threadName%(threadName)sThread Name

그냥 print() 쓰면 되는거 아님?

print() 함수도 콘솔에 로깅하는 방법이다. 하지만 logging 모듈보다 정보 표현이 한정적이며 협업 개발할 때 굉장히 거슬린다…(어느 모듈에서 썼는지도 모르겠는 쓸데없는 콘솔 로그가 계속 뜬다;;)

  • logging 모듈의 장점 정리
    1. error, info, debug 등 로깅 수준을 쉽게 정의할 수 있다.
    2. formatter 를 이용해 개발자가 원하는 형태로 로깅할 수 있다.
    3. 로깅이 실행된 모듈, 클래스, 함수를 추적해 서비스를 추적하기 쉽다.
    4. 로깅 레벨을 정의해서 Dev 환경과 Prod 환경의 로깅 수준을 차별화할 수 있다.

그 밖에도 굉장히 많을 것 같은데 일단 생각나는게 이 정도뿐이다…ㅠ

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