Python如何使用logging為Flask增加logid
我們?yōu)榱藛栴}定位,常見做法是在日志中加入 logid,用于關(guān)聯(lián)一個(gè)請(qǐng)求的上下文。這就涉及兩個(gè)問題:1. logid 這個(gè)“全局”變量如何保存?zhèn)鬟f。2. 如何讓打印日志的時(shí)候自動(dòng)帶上 logid(畢竟不能每個(gè)打日志的地方都手動(dòng)傳入)
logid保存與傳遞傳統(tǒng)做法就是講 logid 保存在 threading.local 里面,一個(gè)線程里都是一樣的值。在 before_app_request 就生成好,logid并放進(jìn)去。
import threading from blueprint.hooks import hooks thread_local = threading.local()app = Flask()app.thread_local = thread_local
import uuid from flask import Blueprintfrom flask import current_app as app hooks = Blueprint(’hooks’, __name__) @hooks.before_app_requestdef before_request(): ''' 處理請(qǐng)求之前的鉤子 :return: ''' # 生成logid app.thread_local.logid = uuid.uuid1().time
因?yàn)樾枰粋€(gè)數(shù)字的 logid 所以簡(jiǎn)單使用 uuid.uuid1().time 一般并發(fā)完全夠了,不會(huì)重復(fù)且趨勢(shì)遞增(看logid就能知道請(qǐng)求的早晚)。
打印日志自動(dòng)帶上logid這個(gè)就是 Python 日志庫(kù)自帶的功能了,可以使用 Filter 來實(shí)現(xiàn)這個(gè)需求。
import logging # https://docs.python.org/3/library/logging.html#logrecord-attributeslog_format = '%(asctime)s %(levelname)s [%(threadName)s-%(thread)d] %(logid)s %(filename)s:%(lineno)d %(message)s'file_handler = logging.FileHandler(file_name)logger = logging.getLogger()logid_filter = ContextFilter()file_handler.addFilter(logid_filter)file_handler.setFormatter(logging.Formatter(log_format))logger.addHandler(file_handler) class ContextFilter(logging.Filter): ''' logging Filter ''' def filter(self, record):'''threading local 獲取logid:param record::return:'''log_id = thread_local.logid if hasattr(thread_local, ’logid’) else ’-’record.logid = log_id return True
log_format 中我們用了很多系統(tǒng)自帶的占位符,但 %(logid)s 默認(rèn)沒有的。每條日志打印輸出前都會(huì)過 Filter,利用此特征我們就可以把 record.logid 賦值上,最終打印出來的時(shí)候就有 logid 了。
雖然最終實(shí)現(xiàn)了,但因?yàn)槭峭ㄓ没桨福杂行?fù)雜了。其實(shí)官方教程中介紹了一種更加簡(jiǎn)單的方式:injecting-request-information,看來沒事還得多看看官方文檔。
以上就是Python如何使用logging為Flask增加logid的詳細(xì)內(nèi)容,更多關(guān)于Python為Flask增加logid的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. idea重置默認(rèn)配置的方法步驟2. IntelliJ IDEA安裝插件的方法步驟3. Docker 部署 Prometheus的安裝詳細(xì)教程4. 通過Django Admin+HttpRunner1.5.6實(shí)現(xiàn)簡(jiǎn)易接口測(cè)試平臺(tái)5. IntelliJ IDEA設(shè)置自動(dòng)提示功能快捷鍵的方法6. IntelliJ IDEA設(shè)置背景圖片的方法步驟7. idea設(shè)置代碼格式化的方法步驟8. idea給項(xiàng)目打war包的方法步驟9. idea打開多個(gè)窗口的操作方法10. IntelliJ IDEA調(diào)整字體大小的方法

網(wǎng)公網(wǎng)安備