2014-04-28 72 views
3

我有Flask安裝程序在發生錯誤時給我發電子郵件,但我想在該電子郵件中包含UserAgent。那可能嗎?我沒有在The docs看到它。有沒有辦法在錯誤日誌中包含useragent?

編輯:該鏈接說更多的東西可以在官方文檔中找到,但不是官方文檔? (flask.readthedocs.org說同樣的事情)

+0

可能與http://stackoverflow.com/questions/9878020/how-do-i-get-the-user-agent-with-flask重複 – xbb

+0

@xbb:我看到了,但我的問題是更具體:如何在錯誤電子郵件中包含UserAgent(或者甚至如何訪問錯誤電子郵件的請求對象)? –

回答

3

我發現如何在this article深處做到這一點。您需要設置一個新的過濾器來將用戶代理添加到記錄中。看起來在過濾階段,您可以使用請求對象來獲取您要查找的內容。所以你實際上沒有過濾任何東西,但是在日誌記錄中添加更多內容。功能示例:

from flask import Flask, request 

app = Flask(__name__) 

if not app.debug: 
    import logging 
    from logging.handlers import SMTPHandler 

    class ContextualFilter(logging.Filter): 
     def filter(self, log_record): 
      log_record.user_agent = request.user_agent 
      return True 

    context_provider = ContextualFilter() 
    app.logger.addFilter(context_provider) 
    mail_handler = SMTPHandler('127.0.0.1', '[email protected]', 
        app.config['ADMINS'], 'Application failed') 
    mail_handler.setFormatter(logging.Formatter(""" 
Message type:  %(levelname)s 
Location:   %(pathname)s:%(lineno)d 
Module:    %(module)s 
Function:   %(funcName)s 
Time:    %(asctime)s 
User-Agent:   %(user_agent)s 

Message: 

%(message)s 
""")) 
    mail_handler.setLevel(logging.ERROR) 
    app.logger.addHandler(mail_handler) 

使用此功能,我可以收到發送給我自己的錯誤日誌的電子郵件。

0

我認爲你的答案是在文檔中單擊一下。檢查出自定義電子郵件格式的this entry。使用示例代碼剪切,添加Flask request對象的導入。使用this question中的方法獲取字符串本身。

from logging import Formatter 
from flask import request 
mail_handler.setFormatter(Formatter(''' 
Message type:  %(levelname)s 
Location:   %(pathname)s:%(lineno)d 
Module:    %(module)s 
Function:   %(funcName)s 
Time:    %(asctime)s 
UserAgent:   %s 

Message: 

%(message)s 
''' % flask.request.user_agent.string)) 

這可能不是完美的(特別是我的字符串格式化代碼),但希望這篇文章點,你在正確的方向。

+0

我收到一個錯誤:RuntimeError:在請求上下文之外工作 –

+0

有趣的是,在創建日誌記錄時,您不能訪問應用程序全局變量。您至少可以獲得LogR​​ecord類的任何[這些](https://docs.python.org/dev/library/logging.html#logging.LogRecord)屬性。我將不得不繼續挖掘,看看是否有辦法在設置mail_handler的階段獲取全局上下文變量。 – voteblake

相關問題