1. 程式人生 > 其它 >[Laravel系列] 框架中增加記錄access log的日誌中介軟體

[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,
        ],

請求一下就會看到生成檔案

開源作品

GO-FLY,一套可私有化部署的免費開源客服系統,安裝過程不超過五分鐘(超過你打我 !),基於Golang開發,二進位制檔案可直接使用無需搭開發環境,下載zip解壓即可,僅依賴MySQL資料庫,是一個開箱即用的網頁線上客服系統,致力於幫助廣大開發者/中小站長快速整合私有客服功能 github地址:go-fly 官網地址:https://gofly.sopans.com

讚賞作者

微信交流