#!/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 from application.common import ConfigHelper class FlaskLoguru: def __init__(self, app=None): """ Initialize the FlaskLoguru instance. If an app is provided, also initialize that app for logging. """ if app is not None: self.init_app(app) def init_app(self, app: Flask) -> None: """ 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 logger.remove() 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 logger.add(sys.stderr, level=level, format=patching) # Register this logger with the app # If the app does not already have an 'extensions' attribute, add one if not hasattr(app, 'extensions'): app.extensions = {} # Initialize the app's 'loguru' extension if it does not already exist app.extensions.setdefault('loguru', {}) # Register this logger with the app's 'loguru' extension app.extensions['loguru'][self] = logger @app.before_request def before_request(): """ A function to run before each request. Logs the start of the 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): """ A function to run after each request. Logs the completion of the request. """ g.logger.info('Request completed') return response @app.teardown_request def teardown_request(exception=None): """ A function to run when ending each request, either because the request was completed or because an error occurred. """ if exception: data = dict( exception=str(exception) ) g.logger = logger.bind(data=data) g.logger.exception('An error occurred during the request')