logger.py 2.95 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
#!/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
崔为之's avatar
崔为之 committed
19
from application.common import ConfigHelper
Weizhi Cui's avatar
Weizhi Cui committed
20 21 22 23


class FlaskLoguru:
    def __init__(self, app=None):
崔为之's avatar
崔为之 committed
24 25 26 27
        """
        Initialize the FlaskLoguru instance.
        If an app is provided, also initialize that app for logging.
        """
Weizhi Cui's avatar
Weizhi Cui committed
28 29 30
        if app is not None:
            self.init_app(app)

崔为之's avatar
崔为之 committed
31
    def init_app(self, app: Flask) -> None:
崔为之's avatar
崔为之 committed
32 33 34 35 36
        """
        Initialize the given app for logging with Loguru.
        This involves setting up a new logger and registering it with the app.
        """
        # Remove any existing handlers from the logger
Weizhi Cui's avatar
Weizhi Cui committed
37
        logger.remove()
崔为之's avatar
崔为之 committed
38 39 40 41 42 43 44 45 46 47

        config_helper = ConfigHelper(app)

        # Fetch the logging configuration from the app's config
        cfg = config_helper.Logger

        # Get the log level from the config, or default to 'DEBUG' if not provided
        level = cfg.Level or 'DEBUG'

        # Add a new handler to the logger with the configured log level
崔为之's avatar
崔为之 committed
48
        logger.add(sys.stderr, level=level, format=patching)
崔为之's avatar
崔为之 committed
49 50 51

        # Register this logger with the app
        # If the app does not already have an 'extensions' attribute, add one
崔为之's avatar
崔为之 committed
52
        if not hasattr(app, 'extensions'):
Weizhi Cui's avatar
Weizhi Cui committed
53 54
            app.extensions = {}

崔为之's avatar
崔为之 committed
55
        # Initialize the app's 'loguru' extension if it does not already exist
崔为之's avatar
崔为之 committed
56
        app.extensions.setdefault('loguru', {})
崔为之's avatar
崔为之 committed
57 58

        # Register this logger with the app's 'loguru' extension
崔为之's avatar
崔为之 committed
59
        app.extensions['loguru'][self] = logger
Weizhi Cui's avatar
Weizhi Cui committed
60 61 62

        @app.before_request
        def before_request():
崔为之's avatar
崔为之 committed
63 64 65 66
            """
            A function to run before each request.
            Logs the start of the request.
            """
Weizhi Cui's avatar
Weizhi Cui committed
67 68 69 70 71 72 73 74 75 76 77
            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):
崔为之's avatar
崔为之 committed
78 79 80 81
            """
            A function to run after each request.
            Logs the completion of the request.
            """
Weizhi Cui's avatar
Weizhi Cui committed
82 83 84 85 86
            g.logger.info('Request completed')
            return response

        @app.teardown_request
        def teardown_request(exception=None):
崔为之's avatar
崔为之 committed
87 88 89 90
            """
            A function to run when ending each request,
            either because the request was completed or because an error occurred.
            """
Weizhi Cui's avatar
Weizhi Cui committed
91 92 93 94 95 96
            if exception:
                data = dict(
                    exception=str(exception)
                )
                g.logger = logger.bind(data=data)
                g.logger.exception('An error occurred during the request')