目錄
- logid保存與傳遞
- 打印日志自動(dòng)帶上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è)線程里都是一樣的值。在 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():
"""
處理請(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-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)沒(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)注腳本之家其它相關(guān)文章!
您可能感興趣的文章:- 解決python logging遇到的坑 日志重復(fù)打印問(wèn)題
- python 實(shí)現(xiàn)logging動(dòng)態(tài)變更輸出日志文件名
- python (logging) 日志按日期、大小回滾的操作
- Python日志打印里logging.getLogger源碼分析詳解
- python 日志模塊logging的使用場(chǎng)景及示例
- Python的logging模塊基本用法
- python 如何對(duì)logging日志封裝
- Python logging自定義字段輸出及打印顏色
- Python中l(wèi)ogging日志的四個(gè)等級(jí)和使用
- Python+logging輸出到屏幕將log日志寫入文件
- Python logging模塊handlers用法詳解