51 lines
1.7 KiB
Python
51 lines
1.7 KiB
Python
|
|
from flask import request, current_app
|
||
|
|
from flask_login import current_user
|
||
|
|
from app.models import AuditLog
|
||
|
|
from functools import wraps
|
||
|
|
import json
|
||
|
|
|
||
|
|
def log_operation(action, target_type, target_id=None, details=None):
|
||
|
|
"""记录操作日志的工具函数"""
|
||
|
|
try:
|
||
|
|
# 获取当前用户信息
|
||
|
|
admin_id = getattr(current_user, 'admin_id', None) if hasattr(current_user, 'is_authenticated') and current_user.is_authenticated else None
|
||
|
|
|
||
|
|
# 获取客户端IP
|
||
|
|
ip_address = request.headers.get('X-Forwarded-For', request.remote_addr)
|
||
|
|
|
||
|
|
# 获取用户代理
|
||
|
|
user_agent = request.headers.get('User-Agent', '')
|
||
|
|
|
||
|
|
# 记录审计日志
|
||
|
|
AuditLog.log_action(
|
||
|
|
admin_id=admin_id,
|
||
|
|
action=action,
|
||
|
|
target_type=target_type,
|
||
|
|
target_id=target_id,
|
||
|
|
details=details,
|
||
|
|
ip_address=ip_address,
|
||
|
|
user_agent=user_agent
|
||
|
|
)
|
||
|
|
except Exception as e:
|
||
|
|
if hasattr(current_app, 'logger'):
|
||
|
|
current_app.logger.error(f"记录操作日志失败: {str(e)}")
|
||
|
|
|
||
|
|
def log_operations(action, target_type):
|
||
|
|
"""记录操作日志的装饰器"""
|
||
|
|
def decorator(f):
|
||
|
|
@wraps(f)
|
||
|
|
def decorated_function(*args, **kwargs):
|
||
|
|
try:
|
||
|
|
# 执行原函数
|
||
|
|
result = f(*args, **kwargs)
|
||
|
|
|
||
|
|
# 记录成功日志
|
||
|
|
log_operation(action, target_type)
|
||
|
|
|
||
|
|
return result
|
||
|
|
except Exception as e:
|
||
|
|
# 记录错误日志
|
||
|
|
log_operation(f"{action}_ERROR", target_type, details={'error': str(e)})
|
||
|
|
raise e
|
||
|
|
return decorated_function
|
||
|
|
return decorator
|