django logging 입문

김혁준·2023년 7월 7일
0

django

목록 보기
16/18

배포 후 서버에러가 터졌는데 status만 나와서 답답했다. 그래서 로깅을 사용하기로 결정!

config/settings.py

if DEBUG == "1":
    DEBUG = False
    LOG_DIR = os.path.join(BASE_DIR, "log")
    LOG_FILE = "/debug.log"
    LOG_PATH = LOG_DIR + LOG_FILE
    LOGGING = {
        "version": 1,
        "disable_existing_loggers": False,
        "handlers": {
            "file": {
                "level": "ERROR",  # 로그 레벨
                "class": "logging.FileHandler",
                "filename": LOG_PATH,  # 로그 경로
            },
        },
        "loggers": {
            "django": {
                "handlers": ["file"],
                "level": "ERROR",
                "propagate": True,
            },
        },
    }

handler와 logger를 정해준다. handler는 어떤 에러를 수집할지 정하고 logger는 결국 로그가 print되는데 어떻게 출력될지를 정해준다.

오류 해결
처음엔 아래 코드를 넣었는데 "Unable to configure root logger" 에러가 뜨면서 서버가 돌아가질 않았다... 구글링 결과!

'root': {
        'handlers': ['console'],
        'level': 'WARNING',
    },

어느 외국인이 gunicorn과 root logger이 버전에 따라 호환이 안된다고 한다! 공식문서에도 있어도 되고 없어도 된다 했음! thanks "danieljacobs1" !
https://github.com/benoitc/gunicorn/issues/2250
https://docs.python.org/3/library/logging.config.html#dictionary-schema-details
해결 완료

filename이 log파일이 들어갈 경로다! LOG_PATH는 결국 os.path.join(BASE_DIR, "log") +"/debug.log"이다! (플젝경로/log/debug.log). 이걸 가지고 docker-compose로 가서 경로설정을 해주자

services:
	backend:
    	volumes:
      - ./backend/django/:/app/
      - ./log/:/app/log/ : ./log/ -> 여기로 이어줘 // /app/log/ 위에서 설정한 debug.log경로

컨테이너 안에 들어가서 로그를 확인하기 귀찮으니 현재 docker-compose.yml이 있는 위치에서 log폴더를 만들고 그 경로에 컨테이너에서 로그파일이 생기는 경로를 이어주자! 그러면 컨테이너에 들어가지 않고도 로그를 확인 할 수 있다

빌드 후 로그 확인!

config/urls.py

def trigger_error(request):
    division_by_zero = 1 / 0
    
urlpatterns = [
    path("debug/", trigger_error),
]

성공적으로 찍힌다! 로깅 입문 완료!

profile
스프링 개발자 지망생입니다

0개의 댓글