c_resource.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package config
  2. import (
  3. "cicv-data-closedloop/common/util"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/sirupsen/logrus"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "time"
  11. )
  12. var resourceLogger *logrus.Logger
  13. // 保存资源占用情况
  14. func SendResourceUsage() {
  15. initLog(LogDir, ResourceLogPrefix)
  16. for {
  17. time.Sleep(time.Duration(10) * time.Second)
  18. top10Cpu, top10Mem := util.GetTop10CpuAndMem()
  19. top10CpuJson, _ := json.MarshalIndent(top10Cpu, "", " ")
  20. top10MemJson, _ := json.MarshalIndent(top10Mem, "", " ")
  21. requestMap := map[string]string{
  22. "totalCpuUsage": util.ToString(util.GetCpuPercent()),
  23. "totalMemoryUsage": util.ToString(util.GetMemoryPercent()),
  24. "top10Process": string(top10CpuJson),
  25. "top10Cpu": string(top10CpuJson),
  26. "top10Mem": string(top10MemJson),
  27. "deviceNumber": LocalConfig.EquipmentNo,
  28. "socIp": LocalConfig.Node.Ip,
  29. }
  30. resourceLogger.Infof("监控信息为:%v", util.MapToReadableJsonString(requestMap))
  31. //responseString, err := util.HttpPostJsonWithHeaders(
  32. // CloudConfig.Monitor.Url,
  33. // map[string]string{"Authorization": "U9yKpD6kZZDDe4LFKK6myAxBUT1XRrDM"},
  34. // requestMap,
  35. //)
  36. //if err != nil {
  37. // c_log.GlobalLogger.Errorf("发送数据监控信息报错%v,响应信息为:%v", err, responseString)
  38. //}
  39. //c_log.GlobalLogger.Infof("发送数据监控信息成功,响应信息为:%v", responseString)
  40. }
  41. }
  42. // 初始化日志配置
  43. func initLog(logDir string, prefix string) {
  44. time.Sleep(time.Duration(1) * time.Second)
  45. // 创建、追加、读写,777,所有权限
  46. logPath := logDir + prefix + "-" + time.Now().Format("2006-01-02-15-04-05") + ".log"
  47. err := util.CreateParentDir(logPath)
  48. if err != nil {
  49. os.Exit(-1)
  50. }
  51. f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_RDWR, os.ModePerm)
  52. if err != nil {
  53. os.Exit(-1)
  54. }
  55. resourceLogger = logrus.New()
  56. resourceLogger.SetOutput(f)
  57. resourceLogger.SetReportCaller(true) // 开启行号显示
  58. resourceLogger.SetFormatter(&logrus.JSONFormatter{
  59. CallerPrettyfier: func(frame *runtime.Frame) (string, string) {
  60. fileName := filepath.Base(frame.File)
  61. return "", fmt.Sprintf("%s:%d", fileName, frame.Line)
  62. },
  63. })
  64. resourceLogger.Info("初始化resourceLogger - 成功")
  65. }