package middleware import ( "IotAdmin/app/system/service/dto" "IotAdmin/common" "IotAdmin/core/sdk/pkg" "bufio" "bytes" "encoding/json" "io" "net/http" "strconv" "strings" "time" extCfg "IotAdmin/config" "IotAdmin/core/sdk" "IotAdmin/core/sdk/api" "IotAdmin/core/sdk/config" "IotAdmin/core/sdk/pkg/jwt-auth/user" "github.com/gin-gonic/gin" "IotAdmin/common/global" ) // LoggerToFile 日志记录到文件 func LoggerToFile(c *gin.Context) { log := api.GetRequestLogger(c) // 开始时间 startTime := time.Now() // 处理请求 var body string switch c.Request.Method { case http.MethodPost, http.MethodPut, http.MethodGet, http.MethodDelete: bf := bytes.NewBuffer(nil) wt := bufio.NewWriter(bf) _, err := io.Copy(wt, c.Request.Body) if err != nil { log.Warnf("copy body error, %s", err.Error()) err = nil } rb, _ := io.ReadAll(bf) c.Request.Body = io.NopCloser(bytes.NewBuffer(rb)) body = string(rb) } c.Next() url := c.Request.RequestURI if strings.Index(url, "logout") > -1 || strings.Index(url, "login") > -1 { return } // 结束时间 endTime := time.Now() if c.Request.Method == http.MethodGet || c.Request.Method == http.MethodOptions { return } rt, bl := c.Get("result") var result = "" if bl { rb, err := json.Marshal(rt) if err != nil { log.Warnf("json Marshal result error, %s", err.Error()) } else { result = string(rb) } } st, bl := c.Get("status") var statusBus = 0 if bl { statusBus = st.(int) } // 请求方式 reqMethod := c.Request.Method // 请求路由 reqUri := c.Request.RequestURI // 状态码 statusCode := c.Writer.Status() // 请求IP clientIP := common.GetClientIP(c) // 执行时间 latencyTime := endTime.Sub(startTime) // 日志格式 logData := map[string]interface{}{ "statusCode": statusCode, "latencyTime": latencyTime, "clientIP": clientIP, "method": reqMethod, "uri": reqUri, } log.WithFields(logData).Info() if c.Request.Method != "OPTIONS" && config.LoggerConfig.EnabledDB && statusCode != 404 { SetDBOperLog(c, clientIP, statusCode, reqUri, reqMethod, latencyTime, body, result, statusBus) } } // SetDBOperLog 写入操作日志表 fixme 该方法后续即将弃用 func SetDBOperLog(c *gin.Context, clientIP string, statusCode int, reqUri string, reqMethod string, latencyTime time.Duration, body string, result string, status int) { oLog := api.GetRequestLogger(c) l := make(map[string]interface{}) l["_fullPath"] = c.FullPath() l["operUrl"] = reqUri l["operIp"] = clientIP l["operLocation"] = pkg.GetLocation(clientIP, extCfg.ExtConfig.AMap.Key) l["operName"] = user.GetUserName(c) l["orgName"] = user.GetOrgName(c) l["requestMethod"] = reqMethod l["operatorType"] = GetFuncMethod(reqUri, reqMethod) l["operParam"] = body l["operTime"] = time.Now() l["jsonResult"] = result l["latencyTime"] = latencyTime.String() l["statusCode"] = statusCode l["userAgent"] = c.Request.UserAgent() l["createBy"] = user.GetUserId(c) l["updateBy"] = user.GetUserId(c) if status == http.StatusOK { l["status"] = dto.OperaStatusEnable } else { l["status"] = dto.OperaStatusDisable } q := sdk.Runtime.GetMemoryQueue(c.Request.Host) message, err := sdk.Runtime.GetStreamMessage("", global.OperateLog, l) if err != nil { oLog.Errorf("GetStreamMessage error, %s", err.Error()) //日志报错错误,不中断请求 } else { err = q.Append(message) if err != nil { oLog.Errorf("Append message error, %s", err.Error()) } } } const ( ADD = iota + 1 UPDATE DELETE EXPORT IMPORT LOGIN LOGOUT AUTH START STOP GEN CLEAN REFRESH ) func GetFuncMethod(url string, method string) string { m := ADD if strings.Index(url, "/api/logout") > -1 { m = LOGOUT } else if strings.Index(url, "/api/login") > -1 { m = LOGIN } else if strings.Index(url, "/api/refresh-token") > -1 { m = LOGIN } else if strings.Index(url, "/import") > -1 { m = IMPORT } else if strings.Index(url, "/export") > -1 { m = EXPORT } else if strings.Index(url, "/auth") > -1 { m = AUTH } else if strings.Index(url, "/start") > -1 { m = START } else if strings.Index(url, "/stop") > -1 { m = STOP } else if strings.Index(url, "/api/sys/gen-") > -1 { m = GEN } else if strings.Index(url, "/clean") > -1 { m = CLEAN } else if strings.Index(url, "/refresh") > -1 { m = REFRESH } else { switch method { case "POST": m = ADD case "PUT": m = UPDATE case "DELETE": m = DELETE default: return "" } } return strconv.Itoa(m) } //func GetApi(c *gin.Context) (*models.SysApi, error) { // db, err := pkg.GetOrm(c) // sysApi := &models.SysApi{} // if err != nil { // log.Errorf("get db error, %s", err.Error()) // response.Error(c, 500, err, "数据库连接获取失败") // return nil, err // } // db.Table(sysApi.TableName()).First(sysApi, "path = ?", c.Request.RequestURI) // return sysApi, nil // //}