實現後臺管理系統的操作日誌功能

yanthink發表於2018-09-03

對於很多後臺管理系統來說,許可權較多,對系統操作的人也會多。如此以來,對於一些操作的記錄就非常有必要了,從而可以清楚的追蹤對系統進行操作的人以及做了哪些操作,並且可以快速排查定位一些問題。

1. 建立中介軟體

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Log;
use Agent;
use Zhuzhichao\IpLocationZh\Ip;

class OperationLog
{
    public function handle(Request $request, Closure $next)
    {
        if (app()->environment('production')) {
            $monolog = Log::getMonolog();
            $logHandlerBak = $monolog->popHandler();
            Log::useDailyFiles(storage_path('logs/operation.log'), 180, 'debug');

            $userString = join(array_filter([user('id'), user('username'), user('realname')]), ' ');
            $uri = $request->path();
            $method = $request->method();
            $userAgent = Agent::getUserAgent();
            $ip = $request->getClientIp();
            $ipInfo = join(array_unique(array_filter(Ip::find($ip))), ' ');
            $queryString = http_build_query($request->except(['password', 'sn', 'token']));
            $logMsg = join([$userString, $method . ' ' . $uri . ' ' . $queryString, $userAgent, $ip, $ipInfo], ' | ');

            Log::info($logMsg . PHP_EOL);

            $monolog->popHandler();
            $monolog->pushHandler($logHandlerBak);
        }

        return $next($request);
    }
}

2. 註冊中介軟體

protected $routeMiddleware = [
   ...
   'operation.log' => Middleware\OperationLog::class,
];

3. 在路由中使用 operation.log 中介軟體

APIRoute::version('v1', [
    'namespace' => 'App\Http\Controllers',
    'middleware' => ['operation.log', 'transform'],
], function () {
    ...
});

操作日誌截圖
file

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章