如何手动发送django异常日志? [英] How to send django exception log manually?

查看:95
本文介绍了如何手动发送django异常日志?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个特定的视图,如果一切都成功完成,并且像 HttpResponseBadRequest() c HttpResponse('') / code>否则。



此视图适用于外部数据,因此可以提出一些意外的异常。
当然我需要知道发生了什么。所以我有这样的样子:

  def my_view(request):
try:
#的代码
return HttpResponse('')
除了:
import logging
logger = logging.getLogger('django.request')
#logger.error(extra = {'request':request})或logger.exception()
返回HttpResponseBadRequest('')

我有一个默认的日志记录配置(django 1.5)。



logger.exception 发送只有一个小回溯,没有请求数据。
logger.error 只发送请求数据。



所以问题是如何完全相同回溯作为django发送(与相同的主题/身体))。
我认为必须有一些干净简单的解决方案,我找不到。



更新



所以使用修补的异常方法我最终得到以下代码:

  logger.exception('Internal Server Error:%s',request.path,
extra = {'status_code':500,'request':request})

其中内置django日志记录产生等效的邮件追溯。

解决方案

此问题是由于最近版本的Python 2.7中已经修复的错误。 此错误意味着异常方法不接受



如果您无法升级到适合最近的Python 2.7,那么您可以补丁在我链接到的问题中引用了修复的Python。如果你不能这样做,你需要对 Logger 进行子类化,并覆盖异常方法来做正确的事情(基本上是将 ** kwargs 添加到异常方法的签名中,该签名被传递到其调用到错误方法。


I have a specific view in my app which should return HttpResponse('') if everything was done successfully and smth like HttpResponseBadRequest() otherwise.

This view works with external data so some unexpected exceptions can be raised. Of course I need to know what happened. So I have smth like that:

def my_view(request):
    try:
        # a lot of code
        return HttpResponse('')
    except:
        import logging
        logger = logging.getLogger('django.request')
        # logger.error(extra={'request': request}) or logger.exception()
        return HttpResponseBadRequest('')

I have a default logging config if it matters (django 1.5).

logger.exception sends only a small traceback and no request data. logger.error sends only request data.

So the question is how to get exactly the same traceback as django sends (with the same subject/body)). I think there must be some clean and simple solution that i just can't find.

UPDATE

So with the patched exception method i ended up with the following code:

logger.exception('Internal Server Error: %s', request.path,
                 extra={'status_code': 500, 'request': request})

which produces equal email traceback as built-in django logging.

解决方案

This problem is due to a bug which has been fixed in recent versions of Python 2.7. This bug meant that the exception method did not accept the extra argument.

If you can't upgrade to a suitably recent Python 2.7, then you can perhaps patch your Python with the fix referenced in the issue I've linked to. If you can't do that, you'll need to subclass Logger and override the exception method to do the right thing (which is basically to add a **kwargs to the exception method's signature, which is passed through to its call to the error method.

这篇关于如何手动发送django异常日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆