前言:
管理员日志管理,添加日志,删除日志。
管理员在后台的每个操作,都记录对应的地址,以及操作参数。
正文:
管理员管理列表页面效果:
控制器代码:controllers/adminLog.go
//日志列表 ,带翻页 func AdminLogList(c *gin.Context) { //获取列表 list := modes.AdminLogList(c) //获取管理员列表 c.HTML(http.StatusOK,"admins/admin_log_list.html", gin.H{ "list":list, "count":len(list), "start_date":c.Query("start_date"), "end_date":c.Query("end_date"), "admin_uname":c.Query("admin_uname"), "ip_addr":c.Query("ip_addr"), }) } //日志详情 func AdminLogDetail(c *gin.Context) { } //删除日志 func AdminLogDel(c *gin.Context) { res,msg := modes.AdminLogDel(c) if res != true { c.JSON(http.StatusOK, gin.H{ "code": 400, "msg": msg,}) return } c.JSON(http.StatusOK, gin.H{ "code": 0, "msg": "删除成功",}) } //批量删除日志 func AdminLogDelBatch(c *gin.Context) { res,msg := modes.AdminLogDelBatch(c) if res != true { c.JSON(http.StatusOK, gin.H{ "code": 400, "msg": msg,}) return } c.JSON(http.StatusOK, gin.H{ "code": 0, "msg": "删除成功",}) }
模型代码:modes/adminsModel.go
//日志记录表 type AdminsLog struct { Id int `form:"id"` AdminUid int `form:"admin_uid"` RequestUrl string `form:"request_url"` RequestMethod string `form:"request_method"` RequestParams string `form:"request_params"` IpAddr string `form:"ip_addr"` AddDatetime string `form:"add_datetime"` } //获取管理员日志列表 func AdminLogList(c *gin.Context) ([]AdminsLog) { log_list := []AdminsLog{} admin :=Admins{} NewDb := DB if admin_uname,isExist := c.GetQuery("admin_uname");isExist == true{ if strings.TrimSpace(admin_uname) != ""{ res := DB.Model(Admins{}).Where("admin_uname=?",admin_uname).Find(&admin) if res.Error == nil { NewDb = NewDb.Where("admin_uid = ?",admin.AdminUid) } } } if ip_addr,isExist := c.GetQuery("ip_addr");isExist == true{ if strings.TrimSpace(ip_addr) != ""{ if strings.Contains(ip_addr,":") { ipa := strings.Split(ip_addr,":") ip_addr = ipa[0] } NewDb = NewDb.Where("ip_addr like ?",ip_addr+"%") } } if start_date,isExist := c.GetQuery("start_date");isExist == true{ if strings.TrimSpace(start_date) != "" { start_date = start_date + " 00:00:00" NewDb = NewDb.Where("add_datetime > ?", start_date) } } if end_date,isExist := c.GetQuery("end_date");isExist == true{ if strings.TrimSpace(end_date) != "" { end_date = end_date+" 23:59:59" NewDb = NewDb.Where("add_datetime <= ?",end_date) } } res := NewDb.Model(AdminsLog{}).Find(&log_list) if res.Error != nil { return log_list } return log_list } //写入登录日志 func AddAdminLog(admin_uid int,c *gin.Context) bool { var url string var params_str string //记录日志 if(strings.Contains(c.Request.RequestURI,"?")){ spurl := strings.Split(c.Request.RequestURI,"?") url = spurl[0] }else{ url = c.Request.RequestURI } if (c.Request.Method == "POST") { if err := c.Request.ParseMultipartForm(32 << 20); err != nil { if !errors.Is(err, http.ErrNotMultipart) { fmt.Println(nil, err) } } var postMap = make(map[string]any, len(c.Request.PostForm)) for k, v := range c.Request.PostForm { if len(v) > 1 { postMap[k] = v } else if len(v) == 1 { postMap[k] = v[0] } } //密码,加密存储 if url == "/admin/dologin" { postMap["passwd"] = common.MyMd5(postMap["passwd"].(string)) } dataType , _ := json.Marshal(postMap) params_str = string(dataType) }else{ query := c.Request.URL.Query() var queryMap = make(map[string]any, len(query)) for k := range query { queryMap[k] = c.Query(k) } dataType1 , _ := json.Marshal(queryMap) params_str = string(dataType1) } admins_log := AdminsLog{ AdminUid: admin_uid, RequestUrl: url, RequestMethod: c.Request.Method, RequestParams: params_str, IpAddr: c.Request.RemoteAddr, AddDatetime: time.Now().Format(common.TimeTem), } res := DB.Model(AdminsLog{}).Create(&admins_log) if res.RowsAffected == 1{ return true } return false } //删除日志 func AdminLogDel(c *gin.Context) (bool,string) { //判断权限 lid := c.PostForm("id") res := DB.Delete(AdminsLog{},lid) if res.Error != nil{ return false,res.Error.Error() } return true,"删除成功" } func AdminLogDelBatch(c *gin.Context) (bool,string) { //判断权限 var ids []string lid := c.PostForm("ids") ids = strings.Split(lid,",") res := DB.Model(AdminsLog{}).Where(" id in ?", ids).Delete(&AdminsLog{}) if res.Error != nil{ return false,res.Error.Error() } return true,"删除成功" }
写入日志调用代码: admins/middleware/adminMid.go
写入管理员日志,是在中间件中调用的。这样能接受到所有请求,并进行调用
//记录日志
modes.AddAdminLog(admins.AdminUid, c)
管理员日志列表视图:admin_log_list.html
<article class="cl pd-20"> <form method="get" action="/admin/admin_log"> <div class="text-c"> 日期范围: <input type="text" onfocus="WdatePicker({maxDate:'#F{$dp.$D(\'logmax\')||\'%y-%M-%d\'}'})" id="logmin" class="input-text Wdate" style="width:120px;" name="start_date" value="{{.start_date}}"> - <input type="text" onfocus="WdatePicker({minDate:'#F{$dp.$D(\'logmin\')}',maxDate:'%y-%M-%d'})" id="logmax" class="input-text Wdate" style="width:120px;" name="end_date" value="{{.end_date}}"> <input type="text" name="admin_uname" id="admin_uname" value="{{.admin_uname}}" placeholder=" 管理员账号" style="width:250px" class="input-text"> <input type="text" name="ip_addr" id="ip_addr" value="{{.ip_addr}}" placeholder=" IP地址 " style="width:250px" class="input-text"> <button name="" id="" class="btn btn-success" type="submit"><i class="Hui-iconfont"></i> 搜资讯</button> </div> </form> <div class="cl pd-5 bg-1 bk-gray mt-20"> <span class="l"> {{ $admin_uid := GetAdminId}} <a href="javascript:;" {{if has_powa $admin_uid "/admin/admin_log_delbatch"}} style="display:none" {{end}} onclick="datadel()" class="btn btn-danger radius"><i class="Hui-iconfont"></i> 批量删除</a> </span> <span class="r">共有数据:<strong>{{.count}}</strong> 条</span> </div> <div class="mt-20"> <table class="table table-border table-bordered table-bg table-hover table-sort"> <thead> <tr class="text-c"> <th width="25"><input type="checkbox" name="" id="checkAll" value=""></th> <th width="80">ID</th> <th width="120">管理员账号</th> <th width="150">请求地址</th> <th width="80">请求方式</th> <th >请求参数</th> <th width="110">IP地址</th> <th width="120">添加时间</th> <th width="120">操作</th> </tr> </thead> <tbody> {{ range $k,$v1 := .list}} <tr class="text-c"> <td><input type="checkbox" value="{{$v1.Id}}" name="lids"></td> <td>{{$v1.Id}}</td> <td >{{AdminsUname $v1.AdminUid}}</td> <td>{{$v1.RequestUrl}}</td> <td>{{$v1.RequestMethod}}</td> <td class="text-l">{{$v1.RequestParams}}</td> <td>{{$v1.IpAddr}}</td> <td >{{$v1.AddDatetime}}</td> <td class="f-14 td-manage"> <a class="ml-5" {{if has_powa $admin_uid "/admin/admin_log_del"}} style="display:none" {{end}} onClick="article_del(this,{{$v1.Id}})" href="javascript:;" title="删除"><i class="Hui-iconfont"></i></a></td> </tr> {{end}} </tbody> </table> </div> </article> <script type="text/javascript"> $('.table-sort').dataTable({ "aaSorting": [[ 1, "desc" ]],//默认第几个排序 "bStateSave": true,//状态保存 "aoColumnDefs": [ //{"bVisible": true, "aTargets": [ 3,4,5 ]} ,//控制列的隐藏显示 {"orderable":false,"aTargets":[0,8]}// 不参与排序的列 ] }); $("#checkAll").click(function (){ if($("#checkAll").prop("checked")==true){ $("input[name='lids']").each(function(){ $(this).prop("checked",true) }) }else{ $("input[name='lids']").each(function(){ $(this).prop("checked",false) }) } }) //批量删除 function datadel(){ var chk_value = [] var flag = 0 $("input[name='lids']").each(function (){ if ($(this).prop("checked") == true){ flag = 1 chk_value.push($(this).val()) } }) if (flag == 0){ layer.alert("请先选择要删除的记录") }else{ var slected = chk_value.join(",") $.post("/admin/admin_log_delbatch",{ids:slected},function (data){ if (data.code == 0){ layer.msg('已批量删除!',{icon:1,time:1000}); window.location.reload() }else{ layer.alert("批量删除失败") } },'json') } } /*资讯-删除*/ function article_del(obj,id){ layer.confirm('确认要删除吗?',function(index){ $.ajax({ type: 'POST', url: '/admin/admin_log_del', dataType: 'json', data:{id:id}, success: function(data){ if (data.code == 0){ $(obj).parents("tr").remove(); layer.msg('已删除!',{icon:1,time:1000}); }else{ layer.alert("删除失败") } }, error:function(data) { console.log(data.msg); }, }); }); } </script>
完结
标签:管理中心,string,admin,res,管理员,date,日志,true From: https://www.cnblogs.com/ypeih/p/17344315.html