![](/img/trans.png)
[英]is this way of using current_user from Flask-Login safe?
[英]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.