实现后台管理系统的操作日志功能

对于很多后台管理系统来说,权限较多,对系统操作的人也会多。如此以来,对于一些操作的记录就非常有必要了,从而可以清楚的追踪对系统进行操作的人以及做了哪些操作,并且可以快速排查定位一些问题。

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 协议》,转载必须注明作者和本文链接
本帖由系统于 5年前 自动加精
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 5

use Agent 这是哪个包

5年前 评论

Call to undefined method Monolog\Logger::getMonolog() 我一直报这个错 $monolog = Log::getMonolog(); dd($monolog);

3年前 评论

@xiayimiaozhongjianni laravel 5.6 以上版本可以通过配置通道实现

// logging.channels.operation 配置
'operation' => [
    'driver' => 'daily',
    'path' => storage_path('logs/operation.log'),
    'level' => 'debug',
    'days' => 180,
], 

// 写入指定通道
Log::channel('operation')->info($logMsg . PHP_EOL); 
3年前 评论
我是王老改 3年前
$ipInfo = join(array_unique(array_filter(Ip::find($ip))), ' '); 

应改为

 $ipInfo = join( '',array_unique(array_filter(Ip::find($ip))));
3年前 评论
yanthink (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!