簡體   English   中英

使用 Flask-Login 時如何將 current_user 的值插入到錯誤日志/電子郵件中?

[英]how could the value of current_user be inserted into error logs/emails when using Flask-Login?

我的應用程序工廠中有以下代碼...

mh = SMTPHandler(
    mailhost=app.config["MAIL_SERVER"],
    fromaddr=app.config["MAIL_DEFAULT_SENDER"],
    toaddrs=app.config["ERRORS_EMAIL"],
    subject="Error",
)
mh.setLevel(logging.ERROR)
app.logger.addHandler(mh)

有什么方法可以將“current_user”的值插入到電子郵件中的某處?

日志輸出添加上下文信息可以通過將Logger對象包裝在LoggerAdapter對象周圍並提供您希望添加的額外信息來完成。 下面是一個說明:

mh = SMTPHandler(
    mailhost=app.config["MAIL_SERVER"],
    fromaddr=app.config["MAIL_DEFAULT_SENDER"],
    toaddrs=app.config["ERRORS_EMAIL"],
    subject="Error",
)
mh.setLevel(logging.ERROR)
mh.setFormatter(logging.Formatter('%(user)s - %(message)s'))
app.logger.addHandler(mh)
app.logger = LoggerAdapter(app.logger, {'user': current_user})

這應該使用其他詳細信息更新SMTPHandler的格式化程序,並將app.logger轉換為LoggerAdapter對象,並以字典形式提供額外信息。

在這種情況下,您可能還會發現Filter符合要求。 它們還可以提供更多的活力,尤其是對於特定於請求的值。 您可以通過繼承Filter類並提供您自己的filter方法實現來使用一個,它應該更新要記錄的記錄:

class CurrentUserFilter(logging.Filter):
    """
    Add a user attribute to all records
    """
    def filter(self, record):
        record.user = current_user
        return True  # Return True to pass the record to the next filter


mh = SMTPHandler(
    mailhost=app.config["MAIL_SERVER"],
    fromaddr=app.config["MAIL_DEFAULT_SENDER"],
    toaddrs=app.config["ERRORS_EMAIL"],
    subject="Error",
)
mh.setLevel(logging.ERROR)
mh.setFormatter(logging.Formatter('%(user)s - %(message)s'))
app.logger.addHandler(mh)
app.logger.addFilter(CurrentUserFilter())

這應該為每條日志記錄添加一個user屬性,而這些屬性又會被格式化程序獲取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM