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

如何扩展Laravel中artisan serve命令的控制台输出内容?

Laravel Artisan Serve 显示请求地址的实现方法

以下是几种实现自定义请求日志输出的原生方案:

方案一:通过自定义中间件记录请求详情

这是最灵活且不修改核心文件的方式:

  1. 创建请求日志中间件
    php artisan make:middleware LogRequestPath
    
  2. 编辑生成的app/Http/Middleware/LogRequestPath.php文件,替换为以下代码:
    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Date;
    
    class LogRequestPath
    {
        public function handle($request, Closure $next)
        {
            $start = microtime(true);
            $response = $next($request);
            $cost = round((microtime(true) - $start) * 1000) . 'ms';
    
            $logContent = sprintf(
                '%s ...%s... ~ %s',
                Date::now()->format('Y-m-d H:i:s'),
                $request->fullUrl(),
                $cost
            );
    
            // 将日志输出到控制台(STDERR对应artisan serve的输出流)
            fwrite(STDERR, $logContent . PHP_EOL);
    
            return $response;
        }
    }
    
  3. 全局注册中间件:打开app/Http/Kernel.php,在$middleware数组末尾添加中间件类:
    protected $middleware = [
        // ... 其他中间件
        \App\Http\Middleware\LogRequestPath::class,
    ];
    
  4. 重启php artisan serve,访问http://127.0.0.1/health,控制台就会输出你期望格式的日志。

方案二:调整Laravel日志配置

如果想复用Laravel的日志系统,可修改config/logging.php配置:

  1. 在channels数组中添加一个自定义控制台通道:
    'custom_console' => [
        'driver' => 'monolog',
        'handler' => \Monolog\Handler\StreamHandler::class,
        'with' => [
            'stream' => 'php://stderr',
        ],
        'formatter' => \Monolog\Formatter\LineFormatter::class,
        'formatter_with' => [
            'format' => '%datetime% ...%extra.url%... ~ %extra.duration%' . PHP_EOL,
            'dateFormat' => 'Y-m-d H:i:s',
        ],
    ],
    
  2. 修改中间件中的日志记录逻辑,使用这个通道并传递额外参数:
    // 替换中间件里的fwrite部分
    \Illuminate\Support\Facades\Log::channel('custom_console')->info('', [
        'url' => $request->fullUrl(),
        'duration' => $cost
    ]);
    
  3. 同样注册中间件后,重启服务即可生效。

注意:不建议直接修改Laravel核心的artisan serve服务代码,因为会影响后续框架更新。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:12:30