Commit 7298d3cb authored by 崔为之's avatar 崔为之 💪🏽

Update project

parent fe0e6f82
...@@ -22,4 +22,11 @@ Elasticsearch: ...@@ -22,4 +22,11 @@ Elasticsearch:
Type: _doc Type: _doc
Logger: Logger:
Type: terminal
Level: DEBUG Level: DEBUG
Path: /Users/cuiweizhi/WorkSpace/Gitlab/elp/logs
Name: elp.log
Format:
Rotation:
Enqueue: True
Retention:
...@@ -14,9 +14,16 @@ import json ...@@ -14,9 +14,16 @@ import json
def serialize(record: dict) -> str: def serialize(record: dict) -> str:
"""Customize logger format""" """
Serializes the log record into a formatted JSON string.
:param record: A dictionary that represents the log record.
:return: A JSON string with the formatted log record.
"""
# Extract and format the timestamp from the record
time_stamp = record["time"] time_stamp = record["time"]
time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S") time_stamp = time_stamp.strftime("%Y-%m-%d %H:%M:%S")
# Construct a subset of the log record with desired fields
subset = { subset = {
"time": time_stamp, "time": time_stamp,
"message": record["message"], "message": record["message"],
...@@ -28,6 +35,11 @@ def serialize(record: dict) -> str: ...@@ -28,6 +35,11 @@ def serialize(record: dict) -> str:
def patching(record: dict) -> str: def patching(record: dict) -> str:
"""Set the patch""" """
Patches the log record by serializing it and adding it to the 'extra' field.
:param record: A dictionary that represents the log record.
:return: A string that represents the patched log record.
"""
record["extra"]["serialized"] = serialize(record) record["extra"]["serialized"] = serialize(record)
return "{extra[serialized]}\n" return "{extra[serialized]}\n"
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
# @Description : # @Description :
""" """
import os
import sys import sys
from flask import Flask, request, g from flask import Flask, request, g
...@@ -22,75 +23,89 @@ from application.common import ConfigHelper ...@@ -22,75 +23,89 @@ from application.common import ConfigHelper
class FlaskLoguru: class FlaskLoguru:
def __init__(self, app=None): def __init__(self, app=None):
""" """
Initialize the FlaskLoguru instance. Construct a new FlaskLoguru instance.
If an app is provided, also initialize that app for logging.
:param app: Optional Flask app to initialize this FlaskLoguru instance for.
""" """
if app is not None: if app is not None:
self.init_app(app) self.init_app(app)
def init_app(self, app: Flask) -> None: def init_app(self, app: Flask) -> None:
""" """
Initialize the given app for logging with Loguru. Initialize the given Flask app for logging.
This involves setting up a new logger and registering it with the app.
:param app: The Flask app to initialize.
""" """
# Remove any existing handlers from the logger
logger.remove()
# Initialize ConfigHelper
config_helper = ConfigHelper(app) config_helper = ConfigHelper(app)
# Fetch the logging configuration from the app's config # Fetch the logging configuration from the app's config
cfg = config_helper.Logger cfg = config_helper.Logger
# Get the log level from the config, or default to 'DEBUG' if not provided # Configure logger based on provided config
level = cfg.Level or 'DEBUG' log_type = cfg.get('Type', 'terminal')
level = cfg.get('Level', 'DEBUG')
path = cfg.get('Path')
name = cfg.get('Name')
_format = cfg.get('Format') or patching
rotation = cfg.get('Rotation', '1 day')
enqueue = cfg.get('Enqueue', False)
retention = cfg.get('Retention', '10 days')
# Add a new handler to the logger with the configured log level # Remove any existing handlers from the logger
logger.add(sys.stderr, level=level, format=patching) logger.remove()
# Register this logger with the app # If the logger type is 'both' or 'file' and a path and a name are provided, add a file logger
# If the app does not already have an 'extensions' attribute, add one if self._should_add_file_logger(log_type, path, name):
if not hasattr(app, 'extensions'): full_path = os.path.join(path, name)
app.extensions = {} logger.add(full_path, level=level, format=_format, rotation=rotation, retention=retention, enqueue=enqueue)
# Initialize the app's 'loguru' extension if it does not already exist # If the logger type is 'both' or 'terminal', add a terminal logger
app.extensions.setdefault('loguru', {}) if self._should_add_terminal_logger(log_type):
logger.add(sys.stderr, level=level, format=_format)
# Register this logger with the app's 'loguru' extension # Register this logger with the app
app.extensions.setdefault('loguru', {})
app.extensions['loguru'][self] = logger app.extensions['loguru'][self] = logger
# Add logger to Flask's before, after and teardown request handlers
@app.before_request @app.before_request
def before_request(): def _log_request_start():
""" """
A function to run before each request. Log the start of the request.
Logs the start of the request.
""" """
data = dict( data = dict(url=request.url, method=request.method, ip=request.remote_addr, request_body=request.get_json())
url=request.url,
method=request.method,
ip=request.remote_addr,
request_body=request.get_json(),
)
g.logger = logger.bind(data=data) g.logger = logger.bind(data=data)
g.logger.info('Request started') g.logger.info('Request started')
@app.after_request @app.after_request
def after_request(response): def _log_request_completion(response):
""" """
A function to run after each request. Log the end of the request.
Logs the completion of the request.
""" """
g.logger.info('Request completed') g.logger.info('Request completed')
return response return response
@app.teardown_request @app.teardown_request
def teardown_request(exception=None): def _log_request_teardown(exception=None):
""" """
A function to run when ending each request, Log any exception that occurred during the request.
either because the request was completed or because an error occurred.
""" """
if exception: if exception:
data = dict( data = dict(exception=str(exception))
exception=str(exception)
)
g.logger = logger.bind(data=data) g.logger = logger.bind(data=data)
g.logger.exception('An error occurred during the request') g.logger.exception('An error occurred during the request')
@staticmethod
def _should_add_file_logger(log_type: str, path: str, name: str) -> bool:
"""
Determine if a file logger should be added.
"""
return log_type in ['both', 'file'] and path and name
@staticmethod
def _should_add_terminal_logger(log_type: str) -> bool:
"""
Determine if a terminal logger should be added.
"""
return log_type in ['both', 'terminal']
...@@ -52,16 +52,13 @@ def create_user(): ...@@ -52,16 +52,13 @@ def create_user():
@user_api.route('/tests', methods=['POST']) @user_api.route('/tests', methods=['POST'])
def test_user(): def test_user():
ch = ConfigHelper(current_app) # data = request.get_json()
print(ch.System) # start = data.get('start')
print(ch.Sys) # end = data.get('end')
data = request.get_json() # dsl = ElasticsearchUtil.dsl(start, end)
start = data.get('start') # index = current_app.config.Elasticsearch.Index
end = data.get('end') # res = ElasticsearchUtil.search(index, dsl)
dsl = ElasticsearchUtil.dsl(start, end) # print(len(res))
index = current_app.config.Elasticsearch.Index
res = ElasticsearchUtil.search(index, dsl)
print(len(res))
data = { data = {
"user_name": "libai", "user_name": "libai",
"user_age": 18, "user_age": 18,
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment