Django error logging: adding request header, body and user information

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

After cleaning the network for several hours, many suggested writing their own middleware, and some suggested writing this information into a separate journal. However, knowing where your code is mistakenly solves one part of the problem, determining which poor soul it affected and what request data was sent during this exception, takes a long way to fix the problem. Having this information in the same log file makes sense to me.

Currently on my view.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)

. , , , .

request.META, request.user.id request.body ?

. , !

+4
2

, , , - . , , , APIView DRF.

. , -

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

. , ( ) META, , , . , , . , , Django.

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

, django HttpRequest. , .

+3

. ...

import logging
from functools import wraps
from django.http import HttpResponse, HttpRequest

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

def log_exceptions(wrapped):
    @wraps(wrapped)
    def wrapper(*args, **kwargs):
        try:
            return wrapped(*args, **kwargs)
        except:
            # log and re-raise
            request = args[0] if len(args) > 0 and isinstance(args[0], HttpRequest) else None
            msg = ("\nuser.id/email: {}/{}\nMETA: {}...\nbody: {}"
                   .format(request.user.id,
                           getattr(request.user, 'email','?'),
                           str(request.META)[:80],
                           request.body)
                   if request
                   else "not a HttpRequest")
            log.exception(msg)
            raise
    return wrapper

@log_exceptions
def random_view(request):
    raise ValueError("simulate a crash")
    if request.user.is_authenticated() and request.user.is_active:
        return HttpResponse('hi')
         # generic view code goes here.
    else:
        return HttpResponse(status=401)

errors.log -

2017-06-27 20:48:09,282: 
user.id/email: 1/test@domain.com
META: {'SESSION_MANAGER': 'local/acb:@/tmp/.ICE-unix/4255,unix/acb:/tmp/.ICE-unix/4255...
body: b''
Traceback (most recent call last):
  File "/home/rod/pyves/rangetest/rangetest/data/views.py", line 14, in wrapper
    return wrapped(*args, **kwargs)
  File "/home/rod/pyves/rangetest/rangetest/data/views.py", line 31, in random_view
    raise ValueError("simulate a crash")
ValueError: simulate a crash

, , , Django errors.log. , Django, , logging config

+2

Source: https://habr.com/ru/post/1679934/


All Articles