#!/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 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): logger.remove() logger.add(sys.stderr, 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')