logger.py 1.74 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8 9 10 11 12
#!/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 :
"""

崔为之's avatar
崔为之 committed
13
import os
Weizhi Cui's avatar
Weizhi Cui committed
14 15 16 17 18 19 20 21 22 23 24 25 26
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)

崔为之's avatar
崔为之 committed
27 28
    def init_app(self, app: Flask) -> None:
        """Initialize the app"""
Weizhi Cui's avatar
Weizhi Cui committed
29
        logger.remove()
崔为之's avatar
崔为之 committed
30 31 32 33 34
        # 获取日志级别
        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'):
Weizhi Cui's avatar
Weizhi Cui committed
35 36
            app.extensions = {}

崔为之's avatar
崔为之 committed
37 38
        app.extensions.setdefault('loguru', {})
        app.extensions['loguru'][self] = logger
Weizhi Cui's avatar
Weizhi Cui committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

        @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')