Laravel 10.x 中间件是记录请求日志的理想位置,需记录请求原始信息与响应结果,使用独立日志通道、敏感数据脱敏、环境/路由条件化输出。

在 Laravel 10.x 中,中间件是记录请求生命周期日志的理想位置——既能捕获进入请求的原始信息(如 IP、URI、方法),也能在响应返回前记录处理结果(如状态码、耗时)。关键在于合理使用 Log 门面或自定义日志通道,并注意避免在日志中泄露敏感数据(如密码、Token)。
基础中间件日志:记录请求与响应概要
创建一个通用日志中间件(例如 LogRequestResponse),在 handle() 方法中记录关键信息:
- 在请求处理前记录方法、URI、客户端 IP、User-Agent
- 在响应返回后记录状态码、响应时间、响应大小
- 使用
microtime(true)计算耗时,确保精度
示例代码片段:
public function handle(Request $request, Closure $next)
{
$startTime = microtime(true);
$ip = $request->ip();
$method = $request->method();
$uri = $request->fullUrl();
<pre class="brush:php;toolbar:false;">Log::info('Request started', [
'ip' => $ip,
'method' => $method,
'uri' => $uri,
'user_agent' => $request->userAgent(),
'timestamp' => now()->toIso8601String()
]);
$response = $next($request);
$duration = round((microtime(true) - $startTime) * 1000, 2);
$statusCode = $response->getStatusCode();
Log::info('Request completed', [
'ip' => $ip,
'method' => $method,
'uri' => $uri,
'status_code' => $statusCode,
'duration_ms' => $duration,
'response_size_kb' => round($response->headers->get('Content-Length') / 1024, 2) ?? 0
]);
return $response;
}
按通道分离日志:避免干扰默认日志流
为中间件日志单独配置一个日志通道(如 middleware),便于集中管理与排查:
- 在
config/logging.php中新增通道,推荐使用daily驱动并设置独立文件路径 - 在中间件中用
Log::channel('middleware')->info(...)写入,不污染stack或single通道 - 可配合日志轮转策略(如只保留 7 天)防止磁盘占用过高
安全过滤:自动脱敏敏感请求参数
直接记录 $request->all() 极易泄露密码、token 等字段。应在日志前主动过滤:
- 定义需屏蔽的键名数组(如
['password', 'token', 'api_key', 'credit_card']) - 使用
$request->except(...)或递归遍历 + 正则匹配(对嵌套数组更稳妥) - 对值做掩码处理(如替换为
***),而非仅移除字段名
例如:
$safeInput = $this->maskSensitiveData($request->all());
Log::channel('middleware')->debug('Request input', $safeInput);
<p>protected function maskSensitiveData($data)
{
$sensitiveKeys = ['password', 'token', 'secret'];
if (!is_array($data)) return $data;</p><pre class="brush:php;toolbar:false;">foreach ($data as $key => $value) {
if (in_array(strtolower($key), $sensitiveKeys)) {
$data[$key] = '***';
} elseif (is_array($value)) {
$data[$key] = $this->maskSensitiveData($value);
}
}
return $data;
}
条件化日志:按环境或路由分组控制输出
开发环境可记录详细信息,生产环境应精简、聚焦异常或慢请求:
- 用
app()->environment(['local', 'staging'])控制是否记录完整输入/输出 - 对特定路由组(如
api/*或后台admin/*)启用增强日志 - 设置耗时阈值(如 >500ms),仅对慢请求记录调试上下文
例如:
if ($duration > 500 && app()->environment('production')) {
Log::channel('slow_requests')->warning('Slow API request', [
'uri' => $uri,
'duration_ms' => $duration,
'memory_usage_mb' => round(memory_get_peak_usage() / 1024 / 1024, 2),
]);
}











