Django错误记录:添加请求标头,正文和用户信息 [英] Django Error Logging: Adding request header, body and user information

查看:50
本文介绍了Django错误记录:添加请求标头,正文和用户信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的错误日志中寻找添加标题,正文和用户电子邮件地址的方法,以及在我的 views.py

Looking for a way to add header, body and a user's email address in my error log along with the stack trace of the exception in my views.py

在搜索了几个小时后,许多人建议编写自己的中间件,还有一些人建议将此类信息记录到单独的日志中.但是,知道您的代码哪里出了错可以解决问题的一部分,确定该异常影响了哪个可怜的人以及在该异常期间发送了哪些请求数据对解决问题有很长的路要走.在同一日志文件中拥有这些信息对我来说很有意义.

After scouring the web for hours, many suggested to write my own middleware and some suggested to log that sort of information into a separate log. However, knowing where your code went wrong solves one part of the problem, identifying which poor soul it affected and what request data was sent during that exception goes a long a way in rectifying the issue. Having that information in the same log file just makes sense to me.

当前在我的views.py中,我有一个简单的设置:

Currently in my views.py, I have this simple setup:

from django.db.models import Min, Max, Q, F, Count, Sum
from django.db import connection
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect
from myapp.models import *
import logging

logging.basicConfig(filename="errors.log",
                    level=logging.ERROR,
                    format='%(asctime)s: %(message)s')


def random_view(request):
    if request.user.is_authenticated() and request.user.is_active:
         # generic view code goes here.
    else:
        return HttpResponse(status=401)

此设置在一段时间内效果很好.每次发生异常时,它都会注销时间,异常错误消息和堆栈跟踪.

This setup worked well for a while. Every time there was an exception, it would log out the time, the exception error message and the stack trace.

如何同时添加request.META,request.user.id和request.body以及堆栈跟踪?

How can I also add in request.META, request.user.id and request.body along with stack trace?

任何建议都会有所帮助.一个可行的答案,甚至更好!

Any suggestions would help. A worked out answer, even better!

谢谢

推荐答案

我认为要解决日志记录问题的完整解决方案是实现中间件.不管是基于类的视图,基于函数的视图还是来自DRF的APIView,该中间件都将能够与您拥有的任何类型的视图实现一起使用.

I think a complete solution to the logging problem you have is to implement a middleware. The middleware would be able to work with any kind of view implementation you have, irrespective of whether it is a class based view, function based view or APIView from DRF.

您可以定义用于完整日志记录的中间件.确保将中间件正确放置在身份验证中间件之后-

You can define a middleware for full logging. Make sure that you place the middleware appropriately after the authentication middleware -

MIDDLEWARE = [
    ...,
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...,
    'path.to.your.middleware.LogMiddleware'
]

在日志中间件中,您可以访问请求和响应.您可以通过记录器存储请求,用户(如果已通过身份验证)和来自请求的所有META属性,或者如果需要,甚至可以将其存储在数据库中.虽然,要注意存储在数据库中是有代价的.您可以通过阅读 Django中间件文档来学习如何编写中间件.a>.

In the log middleware, you would have access to the request and response. You can store request, the user (if authenticated) and all the META properties coming from the request via a logger, or you can even store it in a database if you want. Although, beware that storing in database comes at a cost. You can learn how to write a middleware by going through the Django middleware documentation.

import traceback

class LogMiddleware():
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            return self.get_response(request)
        except:
            if request.user.is_authenticated():
                # Log the user
            path = request.get_full_path() # Get the URL Path
            tb = traceback.format_exc() # Get the traceback
            meta = request.META # Get request meta information
            # Log everything
            raise  # Raise exception again after catching

您可以从HttpRequest .让我知道您是否需要对此进行澄清.

You can read about all the meta attributes present from the django documentation of HttpRequest. Let me know if you need any clarification on this.

这篇关于Django错误记录:添加请求标头,正文和用户信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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