【问题标题】:How do you log server errors on django sites你如何在 django 网站上记录服务器错误
【发布时间】:2010-09-19 06:43:41
【问题描述】:

因此,在进行开发时,我可以将 settings.DEBUG 设置为 True,如果发生错误,我可以看到它的格式很好,并且具有良好的堆栈跟踪和请求信息。

但在某种生产网站上,我宁愿使用DEBUG=False 并向访问者显示一些标准错误 500 页面,其中包含我目前正在修复此错误的信息;)
同时,我想用某种方式将所有这些信息(堆栈跟踪和请求信息)记录到我服务器上的文件中——这样我就可以将它输出到我的控制台并观察错误滚动,将日志通过电子邮件发送给我每小时或类似的时间。

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

【问题讨论】:

标签: python django error-logging


【解决方案1】:

好吧,当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

这确实让您可以访问异常对象,但是,中间件方法更容易使用。

【讨论】:

  • 请注意,使用logging.exception('Some message') 和python 的标准日志记录模块在got_request_exception 的信号处理程序中工作得很好,如果您只想注销堆栈跟踪。也就是说,回溯在got_request_exception 中仍然可用。
  • 传递给 process_exception 的异常似乎没有堆栈跟踪,有没有办法得到它?
【解决方案2】:

如前所述,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
        },
    },
}

【讨论】:

  • 我同意,我爱哨兵!我想拥有它的 .Net 端口(最近一直在从事 .Net 项目)。
  • 'include_html': True 不仅仅是让电子邮件“更好”!它包括完整的回溯,包括设置和局部变量的值。根据文档,这是一个安全问题:docs.djangoproject.com/en/1.8/topics/logging/…
  • 我很好奇 mail_admins 处理程序(和 django.request 记录器)是否是必要的,因为您有 'disable_existing_loggers': False 并且只是使用此处理程序(和记录器)复制默认的 django 日志记录。等我测试完再更新。
  • 请更新此答案。从 django1.9 更改日志:Django 的默认日志配置不再定义“django.request”和“django.security”记录器。
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:

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

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

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

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

    我都用过,效果很好。

    【讨论】:

      【解决方案5】:

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

      【讨论】:

      • 我很好奇 mail_admins 处理程序(和 django.request 记录器)是否是必要的,因为您有 'disable_existing_loggers': False 并且只是使用此处理程序(和记录器)复制默认的 django 日志记录。测试完我会更新的。
      【解决方案6】:

      我的fcgi 脚本出现了一个烦人的问题。它发生在 django 甚至开始之前。缺乏日志记录太痛苦了。无论如何,首先将 stderr 重定向到文件有很大帮助:

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

      【讨论】:

        【解决方案7】:

        您可以在 Python 中使用日志库,无需 pip install 任何东西。

        将任何print() 替换为logging.debug() 但是,

        Django Sentry 是个好方法

        正如 EMP 所说。

        【讨论】:

          猜你喜欢
          • 2017-09-16
          • 2017-09-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-20
          相关资源
          最近更新 更多