You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.4 KiB
57 lines
1.4 KiB
#!/usr/bin/env python
|
|
# encoding: utf-8
|
|
"""
|
|
@author: tx
|
|
@file: log.py
|
|
@time: 2023/6/6 17:03
|
|
@desc:
|
|
"""
|
|
import json
|
|
|
|
from fastapi import Request
|
|
from functools import wraps
|
|
import inspect
|
|
|
|
from helper.logger import logger
|
|
from models.log import Log
|
|
|
|
def _parse_func_doc(info):
|
|
delimiter = ":param" if ":param" in info else ":return"
|
|
result = info.split(delimiter)[0].strip()
|
|
return result
|
|
|
|
def logger_wrapper(func):
|
|
@wraps(func)
|
|
async def wrapper(*args, **kwargs):
|
|
request = kwargs.get("request")
|
|
if not request or not hasattr(request.state, "current_user"):
|
|
interface_user_name, interface_user_id = "", None
|
|
else:
|
|
current_user = request.state.current_user
|
|
interface_user_name, interface_user_id = current_user.name, current_user.id
|
|
|
|
interface_desc = _parse_func_doc(func.__doc__)
|
|
|
|
response = await func(*args, **kwargs)
|
|
response_data = json.loads(response.body)
|
|
|
|
response_msg = response_data.get("desc")
|
|
record = {
|
|
"user_id": interface_user_id,
|
|
"users": interface_user_name,
|
|
"kind": interface_desc,
|
|
"comment": f"访问:{interface_desc}, 返回信息:{response_msg}"
|
|
}
|
|
await record_log(**record)
|
|
|
|
return response
|
|
|
|
return wrapper
|
|
|
|
|
|
async def record_log(**kwargs):
|
|
await Log.create(**kwargs)
|
|
|
|
logger.info(f"{kwargs.get('users')} {kwargs.get('comment')}")
|
|
|