摘要:Flask
,logging
设置日志处理器
在__init__.py
中注册日志对象,使用app.logger
设置日志等级和增加处理器,设置处理器为按照日期切分,最大保留30天。
import os
import logging
from logging.handlers import RotatingFileHandler
from settings import config
def create_app(config_name=None):
if config_name is None:
config_name = os.getenv('FLASK_CONFIG', 'development')
app = Flask('pira_score_web')
app.config.from_object(config[config_name])
def register_logging(app):
app.logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s [%(module)s] %(levelname)s %(message)s', '%Y-%m-%d %H:%M:%S')
time_rotating_handler = TimedRotatingFileHandler('logs/detail.log', when='d', interval=1, backupCount=30,
encoding="utf8", delay=False)
time_rotating_handler.setLevel(logging.INFO)
time_rotating_handler.setFormatter(formatter)
app.logger.addHandler(time_rotating_handler)
register_logging(app)
return app
设置日志格式和生成request_id
为日志生成一个随机ID,同一个请求设计多个服务调用标识为同一个ID,使用uuid模块调用uuid.uuid4().hex
自动生成32位随机ID,存储在钩子函数before_request
的g
对象中,请求结束在after_request
获取从一次请求的g对象中获取request_id,所有日志字段如下:
-
status_code
:状态码response.status_code
-
method
:请求方法request.method
-
ip
:请求头request.headers中有X-Real-IP
就用,没有用request.remote_addr
-
url
:请求的url路径request.url
-
Referer
:从请求头request.headers中获取来源页面 -
agent
:从请求头request.headers中获取User-Agent用户代理 -
requestId
:获取请求的request_id
import uuid
from flask import Flask, g, request
def create_app(config_name=None):
app = Flask('pira_score_web')
...
...
...
@app.before_request
def before_request():
g.requestId = uuid.uuid4().hex
@app.after_request
def after_request(response):
app.logger.info(json.dumps({
"AccessLog": {
"status_code": response.status_code,
"method": request.method,
"ip": request.headers.get('X-Real-IP', request.remote_addr),
"url": request.url,
# "referer": request.headers.get('Referer'),
# "agent": request.headers.get("User-Agent"),
"requestId": str(g.requestId),
}
}, ensure_ascii=False
))
return response
return app
在蓝图中调用
在主程序中已经设置了每次请求结束写入磁盘日志,在蓝图中使用current_app.logger
调用日志对象将报错信息输入日志文件
from flask import Blueprint, render_template, current_app, abort
index = Blueprint('index', __name__)
@index.route('/index', methods=['GET'])
def index_info():
try:
a = 1
except Exception as e:
current_app.logger.error(e)
abort(404)
return render_template('index.html', **locals())