[python] Django 사이트에서 서버 오류를 기록하는 방법

따라서 개발을 할 때 설정할 settings.DEBUGTrue있으며 오류가 발생하면 스택 추적 및 요청 정보가 좋은 형식으로 볼 수 있습니다.

그러나 일종의 생산 사이트에서 나는
현재이 DEBUG=False버그를 수정하기 위해 노력하고 있다는 정보가있는 표준 오류 500 페이지를 사용 하고 방문자에게 보여주고 싶습니다 .)
동시에 모든 로깅 방법을 원합니다. 해당 정보 (스택 추적 및 요청 정보)를 서버의 파일에 저장하면 콘솔로 출력하여 오류 스크롤을 볼 수 있으며 매 시간마다 로그를 전자 메일로 보낼 수 있습니다.

django-site를 위해 어떤 로깅 솔루션을 추천하고 그러한 간단한 요구 사항을 충족합니까? 응용 프로그램을 fcgi서버로 실행하고 있으며 아파치 웹 서버를 프론트 엔드로 사용하고 있습니다 (lighttpd로 갈 생각이지만).



답변

글쎄, DEBUG = FalseDjango는 ADMINS설정에 나열된 각 사람에게 오류의 전체 추적을 자동으로 메일로 보내 므로 거의 무료로 알림을받을 수 있습니다. 보다 세밀한 제어를 원하면라는 메소드를 정의하는 미들웨어 클래스를 작성하여 설정에 추가 할 수 있습니다.이 메소드 process_exception()는 발생한 예외에 액세스 할 수 있습니다.

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

그러면 process_exception()메소드는 콘솔에 쓰기, 파일에 쓰기 등 원하는 로깅 유형을 수행 할 수 있습니다.

편집 : 약간 유용하지는 않지만 got_request_exception요청 처리 중에 예외가 발생할 때마다 전송되는 신호를 수신 할 수도 있습니다.

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

이것은 않습니다 하지 미들웨어 방법으로 작업을 훨씬 더 쉽게 있도록하지만, 예외 객체에 대한 액세스를 제공합니다.


답변

Django Sentry는 이미 언급했듯이 좋은 방법이지만, 별도의 웹 사이트로 올바르게 설정하는 데 약간의 작업이 있습니다. 간단한 텍스트 파일에 모든 것을 기록하려면 여기에 기록 할 로깅 구성이 있습니다.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는 정확하지만 데이터 저장소에 예외를 기록하려는 경우 이미 사용 가능한 몇 가지 오픈 소스 솔루션이 있습니다.

1) CrashLog는 http://code.google.com/p/django-crashlog/를 선택하는 것이 좋습니다 .

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

둘의 차이점은 무엇입니까? 내가 볼 수있는 거의 아무것도 없으므로 어느 쪽이든 충분합니다.

나는 두 가지를 모두 사용했으며 잘 작동합니다.


답변

EMP의 가장 유용한 코드 제출 이후로 시간이 지났습니다. 방금 그것을 구현했고, 버그를 추적하기 위해 일부 manage.py 옵션을 사용하여 문제를 해결하는 동안 현재 버전의 Django (1.5.?)에서 require_debug_false 필터가 있다는 효과에 대한 사용 중단 경고가 나타납니다. mail_admins 핸들러에 필요합니다.

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

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')


답변