#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # @Version : Python 3.11.4 # @Software : Sublime Text 4 # @Author : StudentCWZ # @Email : StudentCWZ@outlook.com # @Date : 2023/10/28 17:44 # @File : logger.py # @Description : """ import os import sys from flask import Flask, request, g from loguru import logger from .format import patching class FlaskLoguru: def __init__(self, app=None): if app is not None: self.init_app(app) def init_app(self, app: Flask) -> None: """Initialize the app""" logger.remove() # 获取日志级别 level = app.config.Logger.Level if app.config.get('Logger') is not None else 'DEBUG' logger.add(sys.stderr, level=level, format=patching) # 注册扩展 if not hasattr(app, 'extensions'): app.extensions = {} app.extensions.setdefault('loguru', {}) app.extensions['loguru'][self] = logger @app.before_request def before_request(): data = dict( url=request.url, method=request.method, ip=request.remote_addr, request_body=request.get_json(), ) g.logger = logger.bind(data=data) g.logger.info('Request started') @app.after_request def after_request(response): g.logger.info('Request completed') return response @app.teardown_request def teardown_request(exception=None): if exception: data = dict( exception=str(exception) ) g.logger = logger.bind(data=data) g.logger.exception('An error occurred during the request')