logger.py 1.54 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#!/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')