问题:如何在Django网站上记录服务器错误

因此,在进行开发时,我可以设置settings.DEBUGTrue,如果发生错误,我可以看到格式正确,具有良好的堆栈跟踪和请求信息。

但是在某种生产站点上,我更愿意使用DEBUG=False并向访问者展示一些标准错误500页,其中包含我目前正在修复此bug的信息;)
同时,我想以某种方式记录所有这些信息(堆栈跟踪和请求信息)存储到服务器上的文件中-因此我可以将其输出到控制台并观看错误滚动,每小时将日志发送给我或类似的东西。

您会为django站点推荐什么样的日志记录解决方案,这些解决方案可以满足那些简单的要求?我有作为fcgi服务器运行的应用程序,并且我使用apache Web服务器作为前端(尽管考虑使用lighttpd)。

So, when playing with the development I can just set settings.DEBUG to True and if an error occures I can see it nicely formatted, with good stack trace and request information.

But on kind of production site I’d rather use DEBUG=False and show visitors some standard error 500 page with information that I’m working on fixing this bug at this moment ;)
At the same time I’d like to have some way of logging all those information (stack trace and request info) to a file on my server – so I can just output it to my console and watch errors scroll, email the log to me every hour or something like this.

What logging solutions would you recomend for a django-site, that would meet those simple requirements? I have the application running as fcgi server and I’m using apache web server as frontend (although thinking of going to lighttpd).


回答 0

好的,当时DEBUG = False,Django会自动将所有错误的完整回溯邮件发送给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

但是,这不能使您访问异常对象,因此中间件方法更容易使用。

Well, when DEBUG = False, Django will automatically mail a full traceback of any error to each person listed in the ADMINS setting, which gets you notifications pretty much for free. If you’d like more fine-grained control, you can write and add to your settings a middleware class which defines a method named process_exception(), which will have access to the exception that was raised:

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

Your process_exception() method can then perform whatever type of logging you’d like: writing to console, writing to a file, etc., etc.

Edit: though it’s a bit less useful, you can also listen for the got_request_exception signal, which will be sent whenever an exception is encountered during request processing:

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

This does not give you access to the exception object, however, so the middleware method is much easier to work with.


回答 1

如前所述,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 Sentry is a good way to go, as already mentioned, but there is a bit of work involved in setting it up properly (as a separate website). If you just want to log everything to a simple text file here’s the logging configuration to put in your 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
        },
    },
}

回答 2

另一个答案中提到的django-db-log已替换为:

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

django-db-log, mentioned in another answer, has been replaced with:

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


回答 3

显然,James是正确的,但是如果您想在数据存储区中记录异常,则已经有一些开源解决方案可用:

1)CrashLog是一个不错的选择:http : //code.google.com/p/django-crashlog/

2)Db-Log也是一个不错的选择:http : //code.google.com/p/django-db-log/

两者有什么区别?我几乎看不到任何东西,所以只要一个就足够了。

我都用过,而且它们运作良好。

Obviously James is correct, but if you wanted to log exceptions in a datastore, there are a few open source solutions already available:

1) CrashLog is a good choice: http://code.google.com/p/django-crashlog/

2) Db-Log is a good choice as well: http://code.google.com/p/django-db-log/

What is the difference between the two? Almost nothing that I can see, so either one will suffice.

I’ve used both and they work well.


回答 4

自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
        },
    },
}

Some time has passed since EMP’s most helpful code submission. I just now implemented it, and while thrashing around with some manage.py option, to try to chase down a bug, I got a deprecation warning to the effect that with my current version of Django (1.5.?) a require_debug_false filter is now needed for the mail_admins handler.

Here is the revised code:

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
        },
    },
}

回答 5

我的fcgi脚本有一个烦人的问题。它发生在django开始之前。缺少伐木非常痛苦。无论如何,将stderr重定向到文件作为第一件事很有帮助:

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

I just had an annoying problem with my fcgi script. It occurred before django even started. The lack of logging is sooo painful. Anyway, redirecting stderr to a file as the very first thing helped a lot:

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。