2012-02-15 3 views
5

Что такое простой способ включить имя пользователя, имя и фамилию и e-amil в django Traceback error.Включить django зарегистрированный пользователь в django Ошибка Traceback

Я знаю, что путь create a custom error report:

  1. Создайте новый класс, который innherit от django.views.debug.SafeExceptionReporterFilter
  2. Set DEFAULT_EXCEPTION_REPORTER_FILTER

Но, что метод а следует переписать получать трассировку с этой информацией?

Я хотел бы, чтобы мой treceback взгляд любит:

Traceback (most recent call last): 

File "/usr...o/core/handlers/base.py", line 89, in get_response 
    response = middleware_method(request) 

File "/.../g...ap/utils/middleware.py", line 23,... 
    if elapsedTime.min > 15: 

TypeError: can't compare datetime.timedelta to int 

Logged user information: 
User: pepito 
name: Pepito Grillo 
e-mail: [email protected] 
+0

Вот уборщик способ: http://stackoverflow.com/a/4946443/565259 – Tobu

+0

@tobu, спасибо много. – danihp

ответ

7

Я сделал это с помощью пользовательского Middleware. Я не уверен, что это лучший ответ, но я решил это для своего проекта.

settings.py:

MIDDLEWARE_CLASSES = (
    ... 
    'utilities.custom_middleware.CustomMiddleware', 
    ... 
) 

утилиты/custom_middleware.py:

from utilities.request import AddRequestDetails 

class CustomMiddleware(object): 
""" 
    Adds user details to request context during request processing, so that they 
    show up in the error emails. Add to settings.MIDDLEWARE_CLASSES and keep it 
    outermost(i.e. on top if possible). This allows it to catch exceptions in 
    other middlewares as well. 
""" 

    def process_exception(self, request, exception): 
     """ 
     Process the request to add some variables to it. 
     """ 

     # Add other details about the user to the META CGI variables. 
     try: 
      if request.user.is_authenticated(): 
       AddRequestDetails(request) 
       request.META['AUTH_VIEW_ARGS'] = str(view_args) 
       request.META['AUTH_VIEW_CALL'] = str(view_func) 
       request.META['AUTH_VIEW_KWARGS'] = str(view_kwargs) 
     except: 
      pass 

утилиты/request.py:

def AddRequestDetails(request): 
""" 
    Adds details about the user to the request, so any traceback will include the 
    details. Good for troubleshooting; this will be included in the email sent to admins 
    on error. 
""" 
if request.user.is_anonymous(): 
    request.META['AUTH_NAME'] = "Anonymous User" 
    request.META['AUTH_USER'] = "Anonymous User" 
    request.META['AUTH_USER_EMAIL'] = "" 
    request.META['AUTH_USER_ID'] = 0 
    request.META['AUTH_USER_IS_ACTIVE'] = False 
    request.META['AUTH_USER_IS_SUPERUSER'] = False 
    request.META['AUTH_USER_IS_STAFF'] = False 
    request.META['AUTH_USER_LAST_LOGIN'] = "" 
else: 
    request.META['AUTH_NAME'] = str(request.user.first_name) + " " + str(request.user.last_name) 
    request.META['AUTH_USER'] = str(request.user.username) 
    request.META['AUTH_USER_EMAIL'] = str(request.user.email) 
    request.META['AUTH_USER_ID'] = str(request.user.id) 
    request.META['AUTH_USER_IS_ACTIVE'] = str(request.user.is_active) 
    request.META['AUTH_USER_IS_SUPERUSER'] = str(request.user.is_superuser) 
    request.META['AUTH_USER_IS_STAFF'] = str(request.user.is_staff) 
    request.META['AUTH_USER_LAST_LOGIN'] = str(request.user.last_login) 
+0

Я буду тестировать. Я вернусь с новостями. – danihp

+0

Я перечитываю ваш пост. Я ищу способ добавить метаинформацию только в исключениях, а не для всех запросов. Чтобы избежать накладных расходов. Что Вы думаете об этом? – danihp

+0

В классе CustomMiddleware вы можете переопределить process_exception и использовать тот же код, что и выше. Просто измените 'def process_view (...' to 'def process_exception (...'. Я не тестировал это, но думаю, что он должен работать. Подробнее о пользовательском промежуточном программном обеспечении здесь: https://docs.djangoproject.com/en/dev/themes/http/middleware/ – Furbeenator

8

Моя тривиальное решение (работает в Джанго 1.5)

settings.py:

MIDDLEWARE_CLASSES = (
    ... 
    'utilities.custom_middleware.UserTracebackMiddleware', 
    ... 
) 

custom_middleware.py:

class UserTracebackMiddleware(object): 
    """ 
    Adds user to request context during request processing, so that they 
    show up in the error emails. 
    """ 
    def process_exception(self, request, exception): 
     if request.user.is_authenticated(): 
      request.META['AUTH_USER'] = unicode(request.user.username) 
     else: 
      request.META['AUTH_USER'] = "Anonymous User" 

надеюсь, что это помогает

+0

Почему преобразование в unicode? –

Смежные вопросы