增加web_api
This commit is contained in:
93
src/gasflux/blueprints/stats.py
Normal file
93
src/gasflux/blueprints/stats.py
Normal file
@ -0,0 +1,93 @@
|
||||
"""
|
||||
Statistics Blueprint
|
||||
Provides API statistics and monitoring endpoints.
|
||||
"""
|
||||
|
||||
import time
|
||||
from flask import Blueprint, current_app
|
||||
|
||||
|
||||
from ..shared import _format_response, log_performance, logger,stats_collector, task_status
|
||||
|
||||
# Create blueprint
|
||||
stats_bp = Blueprint('stats', __name__, url_prefix='/stats')
|
||||
|
||||
|
||||
@stats_bp.route('', methods=['GET'])
|
||||
@log_performance
|
||||
def get_stats():
|
||||
"""Get detailed API statistics and monitoring data."""
|
||||
logger.debug("Statistics requested")
|
||||
|
||||
try:
|
||||
# Get detailed statistics
|
||||
stats_data = stats_collector.get_summary()
|
||||
|
||||
# Add current system information
|
||||
try:
|
||||
import psutil
|
||||
memory = psutil.virtual_memory()
|
||||
disk = psutil.disk_usage(str(current_app.config['OUTPUT_FOLDER']))
|
||||
|
||||
stats_data['system'] = {
|
||||
'memory_usage_percent': memory.percent,
|
||||
'memory_used_gb': round(memory.used / (1024**3), 2),
|
||||
'memory_total_gb': round(memory.total / (1024**3), 2),
|
||||
'disk_usage_percent': disk.percent,
|
||||
'disk_used_gb': round(disk.used / (1024**3), 2),
|
||||
'disk_total_gb': round(disk.total / (1024**3), 2)
|
||||
}
|
||||
except ImportError:
|
||||
# psutil not available
|
||||
stats_data['system'] = {
|
||||
'note': 'System metrics unavailable - install psutil for detailed monitoring'
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to collect system metrics: {e}")
|
||||
stats_data['system'] = {'error': str(e)}
|
||||
|
||||
# Add recent task information
|
||||
recent_tasks = []
|
||||
current_time = time.time()
|
||||
for task_id, task_info in list(task_status.items())[-20:]: # Last 20 tasks
|
||||
age = current_time - task_info.get('updated_at', 0)
|
||||
recent_tasks.append({
|
||||
'task_id': task_id,
|
||||
'status': task_info.get('status'),
|
||||
'age_seconds': round(age, 1),
|
||||
'message': task_info.get('message', '')[:100] # Truncate long messages
|
||||
})
|
||||
|
||||
stats_data['recent_tasks'] = recent_tasks
|
||||
|
||||
return _format_response(200, "统计信息获取成功", stats_data)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to retrieve statistics: {str(e)}", exc_info=True)
|
||||
return _format_response(500, "获取统计信息失败", {
|
||||
"error_details": str(e)
|
||||
})
|
||||
|
||||
|
||||
@stats_bp.route('/reset', methods=['POST'])
|
||||
@log_performance
|
||||
def reset_stats():
|
||||
"""Reset API statistics (admin function)."""
|
||||
logger.warning("Statistics reset requested")
|
||||
|
||||
try:
|
||||
# Reset statistics
|
||||
stats_collector.reset_stats()
|
||||
|
||||
# Log the reset
|
||||
logger.info("API statistics have been reset")
|
||||
|
||||
return _format_response(200, "统计信息重置成功", {
|
||||
"timestamp": time.time()
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to reset statistics: {str(e)}", exc_info=True)
|
||||
return _format_response(500, "重置统计信息失败", {
|
||||
"error_details": str(e)
|
||||
})
|
||||
Reference in New Issue
Block a user