效果展示:
思路:
1、中间件
2、路由加上中间件
3、中间件里获取相关操作、ip、请求参数(转json格式入库),请求类型
4、利用模型进行数据写入
5、数据表设计
示例代码:
1、在所属模块中间件目录middleware下创建OperationLog.php中间件,并编写如下代码
<?php /** * * User: jyblogs * Date: 2021/5/11 * Email: <2938039696@qq.com> * 日志中间件 **/ declare (strict_types=1); namespace app\union\middleware; use app\union\model\Adminlist; use app\union\model\AdminLog; use think\facade\Cookie; class OperationLog { /** * 处理请求 * * @param \think\Request $request * @param \Closure $next * @return Response */ public function handle($request, \Closure $next) { $admin_id = Cookie::get('admin_id'); //管理员id $method = $request->method(); //请求方法比如GET POST $path= $request->url(true); //请求url $ip = $request->ip(); //ip $input = $request->param(); //请求参数 if(!$request->isGet()){ self::writeLog($admin_id,$input,$path,$method,$ip); } return $next($request); } public function writeLog($admin_id,$input,$path,$method,$ip){ $admin = Adminlist::where('id',$admin_id)->find(); if($admin) { $admin_id = $admin['id']; $admin_name = $admin['admin_name']; }else{ return returnJson('500','非法操作'); } $log = new AdminLog; $log->admin_id = $admin_id; $log->admin_name = $admin_name; $log->path = $path; $log->method = $method; $log->ip = $ip; $log->content = json_encode($input, JSON_UNESCAPED_UNICODE); $log->created_at = time(); $log->save(); } } ?>
2、模型代码
<?php namespace app\union\model; use think\facade\Cookie; use think\Model; class Defendlist extends Model { protected $pk = 'id'; // 设置当前模型对应的完整数据表名称 protected $name = 'sys_admin_log'; } ?>
3、使用路由中间件:在路由文件下加入如下代码
<?php ->middleware([\app\union\middleware\OperationLog::class]) ?>
4、附:数据表设计
CREATE TABLE `tp_sys_admin_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `admin_name` varchar(255) DEFAULT NULL COMMENT '账号', `created_at` int(12) DEFAULT NULL COMMENT '操作时间', `ip` varchar(200) CHARACTER SET utf8 DEFAULT NULL COMMENT 'ip', `content` text COMMENT '日志', `admin_id` int(11) DEFAULT NULL COMMENT '账号id', `path` varchar(255) DEFAULT NULL COMMENT '操作路由', `method` varchar(255) DEFAULT NULL COMMENT '操作方法', PRIMARY KEY (`id`) USING BTREE ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='管理员操作日志表';
文章评论(0)