[Laravel系列] 框架中增加记录access log的日志中间件

有时候我们需要记录下请求和响应的全部参数

这样可以方便排查问题

现在通过中间件的形式增加一个AccessLog的记录功能

app\Http\Middleware目录下增加AccessLog.php 文件

<?php

namespace App\Http\Middleware;

use Closure;

class AccessLog
{
    /**
     * 路由全局中间件
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $requestTime = microtime(true);

        $response = $next($request);

        $rq_time = microtime(true) - $requestTime;

        $log = [
            'method' => $request->method(),
            'url' => $request->fullUrl(),
            'param' => json_encode($request->all(), JSON_UNESCAPED_UNICODE),
            'response' => $response->getContent(),
            'req_header' => json_encode($request->header(), JSON_UNESCAPED_UNICODE),
            'resp_header' => json_encode($response->headers->all(), JSON_UNESCAPED_UNICODE),
            'ip_address' => $request->ip(),
            'rq_time' => sprintf("%.2f", $rq_time),
        ];

        logger()->channel('access')->info($log);

        return $response;
    }
}

app/Http/Kernel.php 注册一下\App\Http\Middleware\AccessLog::class

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        \App\Http\Middleware\AccessLog::class
    ];

增加一下配置

config/logging.php

        'access' => [
            'driver' => 'daily',
            'path' => env('LOG_PATH_ACCESS', storage_path('logs/access/laravel.log')),
            'level' => env('LOG_LEVEL', 'debug'),
            'days' => 14,
        ],

请求一下就会看到生成文件 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值