ThinkPHP6全链路日志:构建智能日志分析与异常追踪系统
一、智能日志系统架构设计
基于ThinkPHP6的多维度日志收集方案:
// 自定义日志通道配置 config/log.php
return [
'default' => env('log.channel', 'stack'),
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily', 'elastic'],
],
'elastic' => [
'driver' => 'custom',
'via' => appcommonlibElasticsearchLogger::class,
'index' => 'tp6_logs_'.date('Y-m-d'),
'hosts' => ['localhost:9200'],
],
'request' => [
'driver' => 'daily',
'path' => runtime_path('logs/request/'.date('Ym')),
'level' => 'info',
]
]
];
// 自定义Elasticsearch日志记录器
namespace appcommonlib;
class ElasticsearchLogger {
public function __invoke(array $config)
{
$client = ClientBuilder::create()
->setHosts($config['hosts'])
->build();
return function ($level, $message, $context) use ($client, $config) {
$params = [
'index' => $config['index'],
'body' => [
'@timestamp' => date('c'),
'level' => $level,
'message' => $message,
'context' => $context,
'trace_id' => request()->traceId ?? '',
'ip' => request()->ip(),
'url' => request()->url()
]
];
try {
$client->index($params);
} catch (Exception $e) {
Log::channel('error')->error('ES写入失败', [
'error' => $e->getMessage()
]);
}
};
}
}
核心价值:集中存储、快速检索、多维分析、实时监控
二、全链路追踪实现
1. 请求生命周期追踪
// 全局中间件 app/middleware/TraceMiddleware.php
class TraceMiddleware
{
public function handle($request, Closure $next)
{
$traceId = md5(uniqid('', true));
$request->traceId = $traceId;
// 记录请求开始
Log::withContext(['trace_id' => $traceId]);
Log::channel('request')->info('Request Start', [
'method' => $request->method(),
'path' => $request->pathinfo(),
'params' => $request->param()
]);
$start = microtime(true);
try {
$response = $next($request);
// 记录请求完成
Log::channel('request')->info('Request End', [
'status' => $response->getCode(),
'duration' => round((microtime(true) - $start) * 1000, 2)
]);
return $response;
} catch (Exception $e) {
// 记录异常
Log::channel('error')->error('Request Error', [
'error' => $e->getMessage(),
'stack' => $e->getTraceAsString(),
'duration' => round((microtime(true) - $start) * 1000, 2)
]);
throw $e;
}
}
}
2. 数据库操作追踪
// 数据库监听器 app/event/DbListener.php
class DbListener
{
public function handle($event)
{
$sql = $event->sql;
$time = $event->time;
// 记录慢查询
if ($time > 500) {
Log::channel('sql')->warning('Slow Query', [
'sql' => $sql,
'time' => $time,
'connection' => $event->connection,
'bindings' => $event->bindings
]);
}
// 调试日志
Log::channel('sql')->debug('SQL Query', [
'sql' => $sql,
'time' => $time
]);
}
}
// 注册事件监听 config/app.php
return [
'listen' => [
'DbQuery' => [appeventDbListener::class]
]
];
三、智能分析与可视化
1. 异常智能聚合
// 异常聚合处理器 app/common/lib/ErrorAggregator.php
class ErrorAggregator
{
public static function report(Throwable $e)
{
$fingerprint = self::getFingerprint($e);
$key = 'error:'.$fingerprint;
// Redis计数器递增
$count = Redis::hIncrBy($key, 'count', 1);
if ($count === 1) {
// 首次记录完整信息
Redis::hMSet($key, [
'message' => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine(),
'first_occurred' => date('Y-m-d H:i:s'),
'last_occurred' => date('Y-m-d H:i:s'),
'trace' => json_encode($e->getTrace())
]);
Redis::expire($key, 86400 * 7); // 保留7天
} else {
// 更新最后发生时间
Redis::hSet($key, 'last_occurred', date('Y-m-d H:i:s'));
}
// 发送告警
if ($count % 10 === 0) {
self::sendAlert($fingerprint, $count);
}
}
private static function getFingerprint(Throwable $e)
{
return md5($e->getFile().$e->getLine().$e->getMessage());
}
}
// 全局异常处理 app/ExceptionHandle.php
public function report(Throwable $exception)
{
ErrorAggregator::report($exception);
parent::report($exception);
}
四、生产环境最佳实践
- 日志分级:DEBUG/INFO/WARNING/ERROR分级存储
- 敏感过滤:密码等敏感信息自动脱敏
- 采样策略:生产环境按比例采样降低存储压力
- 自动归档:设置日志自动压缩和过期清理
- 监控告警:基于错误频率设置智能告警