programing

django 사이트에서 서버 오류를 기록하는 방법

minimums 2023. 7. 7. 18:53
반응형

django 사이트에서 서버 오류를 기록하는 방법

따라서 개발을 실행할 때 설정할 수 있습니다.settings.DEBUGTrue오류가 발생하면 올바른 스택 추적 및 요청 정보와 함께 올바르게 포맷된 것을 확인할 수 있습니다.

하지만 생산 현장에서는 차라리DEBUG=False에게 내가 이 와 함께
동시에 모든 정보(스택 추적 및 요청 정보)를 서버의 파일에 기록하여 콘솔에 출력하고 오류가 스크롤되는 것을 보고 매 시간마다 로그를 이메일로 보낼 수 있습니다.

이러한 간단한 요구 사항을 충족할 수 있는 django 사이트에 대해 어떤 로깅 솔루션을 추천하시겠습니까?을 응용프로다같실행다니합이로 하고 있습니다.fcgi서버와 저는 프론트엔드로 아파치 웹 서버를 사용하고 있습니다(라이트tpd로 갈 생각이지만).

음, 제.DEBUG = False장고는 자동으로 오류의 전체 추적을 목록에 있는 각 사용자에게 메일로 보냅니다.ADMINS거의 무료로 알림을 받을 수 있는 설정.보다 세밀한 제어를 원하는 경우, 다음과 같은 방법을 정의하는 미들웨어 클래스를 작성하고 설정에 추가할 수 있습니다.process_exception()제기된 예외에 액세스할 수 있습니다.

http://docs.djangoproject.com/en/dev/topics/http/middleware/ #process-messages

당신의.process_exception()그런 다음 콘솔에 쓰기, 파일에 쓰기 등 원하는 모든 유형의 로깅을 수행할 수 있습니다.

편집: 조금 덜 유용하지만, 당신은 또한 들을 수 있습니다.got_request_exception신호 - 요청 처리 중에 예외가 발생할 때마다 전송됩니다.

http://docs.djangoproject.com/en/dev/ref/signals/ #got-request-message

그러나 이렇게 하면 예외 개체에 액세스할 수 없으므로 미들웨어 방법을 사용하는 것이 훨씬 쉽습니다.

이미 언급했듯이 장고 센트리는 좋은 방법이지만, (별도의 웹사이트로서) 제대로 설정하는 데 관련된 작업이 약간 있습니다. 파일에 합니다.settings.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        # Include the default Django email handler for errors
        # This is what you'd get without configuring logging at all.
        'mail_admins': {
            'class': 'django.utils.log.AdminEmailHandler',
            'level': 'ERROR',
             # But the emails are plain text by default - HTML is nicer
            'include_html': True,
        },
        # Log to a text file that can be rotated by logrotate
        'logfile': {
            'class': 'logging.handlers.WatchedFileHandler',
            'filename': '/var/log/django/myapp.log'
        },
    },
    'loggers': {
        # Again, default Django configuration to email unhandled exceptions
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        # Might as well log any errors anywhere else in Django
        'django': {
            'handlers': ['logfile'],
            'level': 'ERROR',
            'propagate': False,
        },
        # Your own app - this assumes all your logger names start with "myapp."
        'myapp': {
            'handlers': ['logfile'],
            'level': 'WARNING', # Or maybe INFO or DEBUG
            'propagate': False
        },
    },
}

다른 답변에서 언급한 django-db-log가 다음으로 대체되었습니다.

https://github.com/dcramer/django-sentry

분명히 James가 옳지만 데이터스토어에 예외를 기록하려면 이미 몇 가지 오픈 소스 솔루션을 사용할 수 있습니다.

CrashLog는 좋은 선택입니다. http://code.google.com/p/django-crashlog/

Db-Log도 좋은 선택입니다. http://code.google.com/p/django-db-log/

둘 사이의 차이점은 무엇입니까?제가 볼 수 있는 것은 거의 아무것도 없으니, 둘 중 하나면 충분할 것입니다.

저는 둘 다 사용해봤는데 잘 작동합니다.

EMP의 가장 유용한 코드 제출 이후 시간이 지났습니다.방금 구현했고, 관리자들과 함께 고민하는 중이었습니다.py 옵션, 버그를 추적하기 위해 현재 버전의 장고(1.5.?)에서는 mail_admins 핸들러에 require_debug_false 필터가 필요하다는 취지의 사용 중지 경고를 받았습니다.

수정된 코드는 다음과 같습니다.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
         'require_debug_false': {
             '()': 'django.utils.log.RequireDebugFalse'
         }
     },
    'handlers': {
        # Include the default Django email handler for errors
        # This is what you'd get without configuring logging at all.
        'mail_admins': {
            'class': 'django.utils.log.AdminEmailHandler',
            'level': 'ERROR',
            'filters': ['require_debug_false'],
             # But the emails are plain text by default - HTML is nicer
            'include_html': True,
        },
        # Log to a text file that can be rotated by logrotate
        'logfile': {
            'class': 'logging.handlers.WatchedFileHandler',
            'filename': '/home/username/public_html/djangoprojectname/logfilename.log'
        },
    },
    'loggers': {
        # Again, default Django configuration to email unhandled exceptions
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        # Might as well log any errors anywhere else in Django
        'django': {
            'handlers': ['logfile'],
            'level': 'ERROR',
            'propagate': False,
        },
        # Your own app - this assumes all your logger names start with "myapp."
        'myapp': {
            'handlers': ['logfile'],
            'level': 'DEBUG', # Or maybe INFO or WARNING
            'propagate': False
        },
    },
}

나는 단지 짜증나는 문제가 있었습니다.fcgi대본.장고가 시작하기도 전에 일어난 일입니다.벌목 부족은 너무 고통스럽습니다.어쨌든 stderr을 파일로 리디렉션하는 것이 가장 먼저 도움이 되었습니다.

#!/home/user/env/bin/python
sys.stderr = open('/home/user/fcgi_errors', 'a')

Python에서 로깅 라이브러리를 사용할 수 있습니다.pip install아무거나.

아무 것이나print()와 함께logging.debug()그렇지만,

장고 보초는 좋은 방법입니다.

EMP의 말대로

언급URL : https://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites

반응형