在 Laravel 中实现可视化监控,可以通过以下 5 层架构构建完整的监控体系:
架构设计
一、数据采集层
1. HTTP 请求监控
创建全局中间件记录请求指标:
// app/Http/Middleware/MonitorRequests.php
public function handle(Request $request, Closure $next)
{
$start = microtime(true);
$response = $next($request);
$duration = microtime(true) - $start;
DB::table('request_metrics')->insert([
'method' => $request->method(),
'path' => $request->path(),
'status_code' => $response->getStatusCode(),
'duration' => $duration,
'ip' => $request->ip(),
'created_at' => now()
]);
return $response;
}
2. 异常监控
在异常处理类中记录:
// app/Exceptions/Handler.php
public function report(Throwable $e)
{
DB::table('error_logs')->insert([
'message' => $e->getMessage(),
'stack_trace' => $e->getTraceAsString(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'created_at' => now()
]);
parent::report($e);
}
二、数据存储层
1. 时序数据表结构
Schema::create('system_metrics', function (Blueprint $table) {
$table->id();
$table->string('metric_name'); // CPU/Memory/QueueSize
$table->double('value');
$table->timestamp('timestamp');
});
Schema::create('business_metrics', function (Blueprint $table) {
$table->id();
$table->string('type'); // sms_sent/sms_failed/payment
$table->integer('count')->default(0);
$table->date('date');
});
2. 定时采集系统指标
创建 Artisan 命令:
// app/Console/Commands/CollectSystemMetrics.php
public function handle()
{
$cpuUsage = sys_getloadavg()[0];
$memoryUsage = memory_get_usage(true) / 1024 / 1024;
DB::table('system_metrics')->insert([
['metric_name' => 'cpu', 'value' => $cpuUsage, 'timestamp' => now()],
['metric_name' => 'memory', 'value' => $memoryUsage, 'timestamp' => now()]
]);
}
三、可视化呈现层
方案1:使用 Grafana + Prometheus
- 安装 Prometheus 客户端
comrequire promphp/prometheus_client_php
- 暴露指标接口
// routes/metrics.php
Route::get('/metrics', function() {
$registry = new CollectorRegistry(new InMemory());
$counter = $registry->getOrRegisterCounter(
'app',
'http_requests_total',
'Total HTTP requests',
['method', 'endpoint', 'status']
);
// 从数据库获取数据填充指标
$requests = DB::table('request_metrics')->get();
foreach ($requests as $request) {
$counter->incBy(1, [
$request->method,
$request->path,
$request->status_code
]);
}
return response($registry->getMetricFamilySamples())
->header('Content-Type', 'text/plain');
});
- Grafana 仪表板配置
# prometheus.yml 配置
scrape_configs:
- job_name: 'laravel'
static_configs:
- targets: ['laravel-app:9600']
方案2:使用内置视图
创建监控面板视图:
// resources/views/admin/metrics.blade.php
<div class="grid grid-cols-4 gap-4">
<div class="bg-white p-4 shadow">
<h3>实时请求频率</h3>
<canvas id="requestsChart"></canvas>
</div>
<div class="bg-white p-4 shadow">
<h3>系统资源</h3>
<div id="cpuGauge"></div>
<div id="memoryGauge"></div>
</div>
</div>
@push('scripts')
<script>
// 使用 Chart.js 展示请求趋势
new Chart(document.getElementById('requestsChart'), {
type: 'line',
data: {
labels: {!! $requestTimes->pluck('time') !!},
datasets: [{
label: '请求延迟(ms)',
data: {!! $requestTimes->pluck('duration') !!}
}]
}
});
</script>
@endpush
四、报警通知层
1. 异常阈值检测
创建监控任务:
// app/Console/Commands/MonitorSystem.php
public function handle()
{
// 检测错误率
$errorCount = DB::table('error_logs')
->where('created_at', '>', now()->subMinutes(5))
->count();
if ($errorCount > 20) {
Notification::route('slack', config('services.slack.webhook'))
->notify(new HighErrorRate($errorCount));
}
// 检测队列积压
$queueSize = DB::table('jobs')->count();
if ($queueSize > 1000) {
Mail::to('admin@example.com')->send(new QueueBacklogAlert($queueSize));
}
}
2. 报警规则配置
// config/monitoring.php
return [
'alerts' => [
'error_rate' => [
'threshold' => 20,
'time_window' => 5, // 分钟
'channels' => ['slack', 'email']
],
'queue_backlog' => [
'threshold' => 1000,
'channels' => ['sms']
]
]
];
五、优化方案对比
方案 | 优点 | 缺点 | 适用场景 |
---|---|---|---|
Grafana + Prometheus | 专业级可视化,实时性强 | 部署复杂,需要维护 | 中大型生产环境 |
内置 Blade 视图 | 开发快速,无需额外依赖 | 功能有限,扩展性差 | 小型项目/内部系统 |
第三方 SaaS | 免运维,开箱即用 | 有数据外泄风险 | 合规允许的敏感度低场景 |
扩展监控维度
- 业务指标监控
// 在短信发送逻辑中添加
DB::table('business_metrics')->updateOrInsert(
['type' => 'sms_sent', 'date' => now()->format('Y-m-d')],
['count' => DB::raw('count + 1')]
);
- 用户行为分析
// 记录用户操作事件
event(new UserAction(
auth()->id(),
'sent_sms',
['phone' => $request->phone]
));
- 分布式追踪
集成 OpenTelemetry:
comrequire open-telemetry/opentelemetry
通过以上方案可实现:
- ✅ 实时系统健康监控
- ✅ 历史数据分析
- ✅ 多维度报警机制
- ✅ 业务指标可视化
- ✅ 从基础设施到应用层的完整观测