You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel 8中禁用请求日志?

禁用Laravel冗余请求日志(无需修改vendor代码)

既然Nginx已经配置了完善的请求日志,完全可以通过以下几种方式禁用Laravel的冗余请求日志(比如健康检查类的404请求日志),且不需要修改vendor目录下的代码:

方法一:通过日志处理器过滤指定请求

  1. 修改config/logging.php中目标日志通道的配置,添加tap选项指定自定义处理器:
'channels' => [
    'single' => [
        'driver' => 'single',
        'path' => storage_path('logs/laravel.log'),
        'level' => env('LOG_LEVEL', 'debug'),
        'replace_placeholders' => true,
        'tap' => [App\Logging\FilterRequestLogs::class], // 新增这行
    ],
],
  1. 创建自定义处理器类App\Logging\FilterRequestLogs:
<?php

namespace App\Logging;

use Monolog\Processor\ProcessorInterface;

class FilterRequestLogs implements ProcessorInterface
{
    public function __invoke(array $record): array
    {
        // 过滤目标请求:这里以GET /index.php的404请求为例
        if (isset($record['context']['request'], $record['context']['response'])) {
            $request = $record['context']['request'];
            $response = $record['context']['response'];
            
            if ($request->method() === 'GET' 
                && $request->path() === 'index.php' 
                && $response->getStatusCode() === 404) {
                return []; // 返回空数组即可跳过这条日志记录
            }
        }

        return $record;
    }
}

方法二:使用中间件拦截日志记录

  1. 创建中间件app/Http/Middleware/DisableRequestLogging.php:
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Log\Logger;

class DisableRequestLogging
{
    protected $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Request $request, Closure $next)
    {
        // 匹配需要过滤的请求规则
        if ($request->isMethod('GET') && $request->path() === 'index.php') {
            // 给日志添加临时处理器,过滤当前请求的日志
            $this->logger->getLogger()->pushProcessor(function ($record) {
                return [];
            });
        }

        return $next($request);
    }
}
  1. 在app/Http/Kernel.php中注册该中间件,可根据需求添加到全局中间件、web组或api组,或指定路由单独使用:
protected $middlewareGroups = [
    'web' => [
        // ...其他中间件
        \App\Http\Middleware\DisableRequestLogging::class,
    ],
];

方法三:调整日志级别(谨慎使用)

如果这类冗余日志属于debug级别,可以在.env中提高日志级别,比如:

LOG_LEVEL=info

但这种方式会过滤所有debug级别的日志,可能影响其他有用的调试信息,仅适合不需要debug日志的生产环境。

内容的提问来源于stack exchange,提问作者qu1j0t3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:40:29