2011-07-13 70 views

回答

14

如果你不想使用的哨兵,你可以使用這個簡單的中間件武官用戶的相關信息的錯誤郵件:

# source: https://gist.github.com/646372 
class ExceptionUserInfoMiddleware(object): 
    """ 
    Adds user details to request context on receiving an exception, 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 exception. 

     :Parameters: 
      - `request`: request that caused the exception 
      - `exception`: actual exception being raised 
     """ 

     try: 
      if request.user.is_authenticated(): 
       request.META['USERNAME'] = str(request.user.username) 
       request.META['USER_EMAIL'] = str(request.user.email) 
     except: 
      pass 

您可以簡單地把這個類的* .py文件的任何地方在您的Django項目下方添加對MIDDLEWARE_CLASSES的引用。即如果你把它放在項目根目錄(你的settings.py所在的位置)的文件「中間件」中,你只需添加middleware.ExceptionUserInfoMiddleware即可。

+0

這看起來很簡單。所以它所做的只是將這兩個值添加到Django將包含在電子郵件中的東西中?然後Django通常發送電子郵件? – Greg

+0

我會把這個類放在什麼文件中?然後我只是將它導入並從settings.py中引用它? – Greg

+0

@Greg我已經更新了答案。 –