data.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package iotLog
  2. import (
  3. "IotAdmin/core/sdk/config"
  4. "IotAdmin/core/tools/writer"
  5. iotStruct "IotAdmin/iot/struct"
  6. "encoding/json"
  7. "log"
  8. "strings"
  9. "time"
  10. )
  11. func init() {
  12. mp = make(map[string]*writer.FileWriter)
  13. }
  14. // LogData 记录数据日志
  15. func LogData(data *iotStruct.CollectData, cfg *iotStruct.ReportConfig, dataStr *string) {
  16. output := getWrite(data)
  17. logData := &iotStruct.LogData{
  18. Time: time.Now().Format("20060102150400"),
  19. No: data.SlaveConfig.No,
  20. Data: *data,
  21. ReportHost: cfg.Host,
  22. ReportProtocol: cfg.Protocol,
  23. ReportMn: cfg.MN,
  24. ReportUser: cfg.User,
  25. ReportPwd: cfg.Pwd,
  26. ReportStr: *dataStr,
  27. }
  28. str, err := json.Marshal(logData)
  29. if err != nil {
  30. log.Printf("Report Log Marshal error: %s \r\n", err.Error())
  31. return
  32. }
  33. _, err = output.Write(str)
  34. if err != nil {
  35. log.Printf("Report Log Write error: %s \r\n", err.Error())
  36. return
  37. }
  38. _, err = output.Write([]byte("\r\n"))
  39. }
  40. var mp map[string]*writer.FileWriter
  41. func getWrite(data *iotStruct.CollectData) *writer.FileWriter {
  42. path := getDataLogPath()
  43. path += strings.ReplaceAll(data.SlaveConfig.No, "_", "/")
  44. var output *writer.FileWriter
  45. var ok bool
  46. if output, ok = mp[path]; !ok {
  47. var err error
  48. output, err = writer.NewFileWriter(
  49. writer.WithPath(path),
  50. // 不切割文件
  51. writer.WithCap(0),
  52. writer.WithSuffix(".data"),
  53. )
  54. if err != nil {
  55. log.Printf("Report Log setup error: %s \r\n", err.Error())
  56. }
  57. mp[path] = output
  58. }
  59. return output
  60. }
  61. func getDataLogPath() string {
  62. path := config.ApplicationConfig.DataLogFile
  63. if path == "" {
  64. path = "./_data/iot/"
  65. } else if path[len(path)-1] != '/' {
  66. path += "/"
  67. }
  68. return path
  69. }