Python如何使用logging為Flask增加logid
我們?yōu)榱藛?wèn)題定位,常見(jiàn)做法是在日志中加入 logid,用于關(guān)聯(lián)一個(gè)請(qǐng)求的上下文。這就涉及兩個(gè)問(wèn)題:1. logid 這個(gè)“全局”變量如何保存?zhèn)鬟f。2. 如何讓打印日志的時(shí)候自動(dòng)帶上 logid(畢竟不能每個(gè)打日志的地方都手動(dòng)傳入)
logid保存與傳遞傳統(tǒng)做法就是講 logid 保存在 threading.local 里面,一個(gè)線(xiàn)程里都是一樣的值。在 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 來(lái)實(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)沒(méi)有的。每條日志打印輸出前都會(huì)過(guò) Filter,利用此特征我們就可以把 record.logid 賦值上,最終打印出來(lái)的時(shí)候就有 logid 了。
雖然最終實(shí)現(xiàn)了,但因?yàn)槭峭ㄓ没桨?,所以有些?fù)雜了。其實(shí)官方教程中介紹了一種更加簡(jiǎn)單的方式:injecting-request-information,看來(lái)沒(méi)事還得多看看官方文檔。
以上就是Python如何使用logging為Flask增加logid的詳細(xì)內(nèi)容,更多關(guān)于Python為Flask增加logid的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 詳解瀏覽器的緩存機(jī)制2. 微信開(kāi)發(fā) 網(wǎng)頁(yè)授權(quán)獲取用戶(hù)基本信息3. asp批量添加修改刪除操作示例代碼4. jsp實(shí)現(xiàn)登錄驗(yàn)證的過(guò)濾器5. HTML5 Canvas繪制圖形從入門(mén)到精通6. css代碼優(yōu)化的12個(gè)技巧7. jsp EL表達(dá)式詳解8. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法9. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))10. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)
