我們?yōu)榱藛栴}定位,常見做法是在日志中加入 logid,用于關(guān)聯(lián)一個請求的上下文。這就涉及兩個問題:1. logid 這個“全局”變量如何保存?zhèn)鬟f。2. 如何讓打印日志的時(shí)候自動帶上 logid(畢竟不能每個打日志的地方都手動傳入)
傳統(tǒng)做法就是講 logid 保存在 threading.local 里面,一個線程里都是一樣的值。在 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 Blueprint from flask import current_app as app hooks = Blueprint('hooks', __name__) @hooks.before_app_request def before_request(): """ 處理請求之前的鉤子 :return: """ # 生成logid app.thread_local.logid = uuid.uuid1().time
因?yàn)樾枰粋€數(shù)字的 logid 所以簡單使用 uuid.uuid1().time 一般并發(fā)完全夠了,不會重復(fù)且趨勢遞增(看logid就能知道請求的早晚)。
這個就是 Python 日志庫自帶的功能了,可以使用 Filter 來實(shí)現(xiàn)這個需求。
import logging # https://docs.python.org/3/library/logging.html#logrecord-attributes log_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)沒有的。每條日志打印輸出前都會過 Filter,利用此特征我們就可以把 record.logid 賦值上,最終打印出來的時(shí)候就有 logid 了。
雖然最終實(shí)現(xiàn)了,但因?yàn)槭峭ㄓ没桨?,所以有些?fù)雜了。其實(shí)官方教程中介紹了一種更加簡單的方式:injecting-request-information,看來沒事還得多看看官方文檔。
以上就是Python如何使用logging為Flask增加logid的詳細(xì)內(nèi)容,更多關(guān)于Python為Flask增加logid的資料請關(guān)注腳本之家其它相關(guān)文章!
標(biāo)簽:隨州 天水 錦州 西安 日照 白城 股票 安慶
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Python如何使用logging為Flask增加logid》,本文關(guān)鍵詞 Python,如何,使用,logging,為,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。