感触life

Laravel5/6/7/8记录接口日志

功能介绍:项目前后端分离,故对请求的接口做日志插表记录,为减少查询路由菜单名直接把接口名写到路由文件

原理:请求接口->到达路由->路由指定log中间件->log中间件插表

1.log表设计

2.路由文件web.php

//指定登录验证中间件与log中间件,其中:2是指定type,可以判断路由为哪个客户端
Route::middleware(['login.merch','log:2'])->group(function () {
    //定义路由中文别名,用于log表的title
    Route::put('/user/save_info', [MerchSubUserController::class, 
    'saveInfo'])->name('保存个人信息');
    //定义资源路由中文别名
    Route::resource('merch_sub/user',MerchSubUserController::class, ['names' 
=> [
            'index'   => '账户列表',
            'store'   => '新增账户',
            'show'    => '账户详情',
            'update'  => '编辑账户',
            'destroy' => '删除账户'
    ]]);
});

3.为中间件指定名称,打开app/Http/Kernel.php

//为log中间件添加别名(这步可以跳过,直接在路由指定该文件)
protected $routeMiddleware = [
        'login.merch' => \App\Http\Middleware\LoginMerch::class,
        'log'  => \App\Http\Middleware\AdminLog::class,
    ];

4.创建表模型, AdminLogModel.php

5.中间件代码,创建app\Http\Middleware\AdminLog.php

class AdminLog
{
    //下面方法已精简业务数据
    public function handle($request, Closure $next,$type)
    {
        $response = $next($request);
        
        $method = $request->method();
        $path = $request->path(); 
        $input = $request->all();   //发送的数据
        $ip = $request->ip();  //操作的IP
    
        //如果新增,更新,删除,则保存到数据库
        if (in_array($method, array('POST','PUT','DELETE'))){
            //$res = json_decode(json_encode($response), true);//返回全部结果
            $log = new \App\Models\AdminLogModel();
            $log->setAttribute('url', $path);
            $log->setAttribute('method', $method);
            $log->setAttribute('title', request()->route()->getName());
            //$log->setAttribute('ip', $ip);
            $log->setAttribute('type', $type);
            $log->setAttribute('content', json_encode($input, 256));
            $log->save();
        }
        return $response;
    }
码字很辛苦,转载请注明来自感触life-博客《Laravel5/6/7/8记录接口日志》

评论