Laravel 和 lumen 自定义每次请求日志输出格式

1、在app/Providers 文件下新建LogServiceProvider.php

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;


class LogServiceProvider extends ServiceProvider
{
    public function boot(){
        $addr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
        $requestId = md5(time() . rand(1 , 1000));
        $file = env('LOG_FILE_PATH') ? env('LOG_FILE_PATH') : storage_path("logs/lumen.log");
        $outInput = "[%datetime%][ip:$addr][requestId:{$requestId}][Level:%level_name%][Message:%message% %context% %extra%]\n";
        $handlers[] = (new RotatingFileHandler($file, 5))
            ->setFormatter(new LineFormatter($outInput, 'Y-m-d H:i:s' , true, true));
        $this->app['log']->setHandlers($handlers);
    }
}

2.在app/Http/Middleware文件下,注册一个中间件新建ApplicatiionLog.php

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class ApplicationLog
{

    public function __construct()
    {
    }

    /**
     * @param $request
     * @param Closure $next
     * @param null $guard
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $array = [
            'params' => $request->all(),
            'header' => $request->header(),
            'method' => $request->method(),
        ];

        Log::info('Uri:' . $request->path(), $array);
        return $next($request);
    }
}

3、加入lumen 中注册中间件

找到booststrap/app.php 中的middleware加上

 App\Http\Middleware\ApplicationLog::class

 $app->middleware([
   //  App\Http\Middleware\ExampleMiddleware::class
     App\Http\Middleware\ApplicationLog::class

 ]);

4、结果如下:

在storage/app/日志文件.log

[2019-10-25 07:15:30][ip:10.10.10.154][requestId:2b44adb1d9c515c465f8212bd4539d6a][Level:INFO][Message:Uri:goods {"params":{"s":"//goods"},"header":{"connection":["keep-alive"],"accept-encoding":["gzip, deflate"],"cookie":["laravel_session=r5fHi3Vz9e8eqxbcqGY84z5FZXRCxplCmPtKMvZ7"],"host":["10.10.10.114:8083"],"accept":["*/*"],"user-agent":["PostmanRuntime/7.6.0"],"postman-token":["1e202dd7-59e0-4a25-bacd-75909efa46ee"],"cache-control":["no-cache"],"content-length":[""],"content-type":[""]},"method":"GET"} ]

 

最新回复(0)
/jishupxnx_2Ftbvn3bt5bYlCG9UjM0NtUfadKJKdLXOhQ_3D_3D2706188
8 简首页