logger.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package logger
  2. import (
  3. "fmt"
  4. "os"
  5. "sort"
  6. "sync"
  7. "time"
  8. )
  9. // TimeFormatDay - format of the day for timestamps
  10. const TimeFormatDay = "2006-01-02"
  11. // TimeFormat - total time format
  12. const TimeFormat = "2006-01-02 15:04:05"
  13. // == fields ==
  14. var currentLogs = make(map[string]string)
  15. var mu sync.Mutex
  16. // Log - handles adding logs
  17. func Log(verbosity int, message ...string) {
  18. mu.Lock()
  19. defer mu.Unlock()
  20. var currentTime = time.Now()
  21. var currentMessage = MakeString(" ", message...)
  22. if int32(verbosity) <= getVerbose() && getVerbose() >= 0 {
  23. fmt.Printf("[netmaker] %s %s \n", currentTime.Format(TimeFormat), currentMessage)
  24. }
  25. currentLogs[currentMessage] = currentTime.Format("2006-01-02 15:04:05.999999999")
  26. }
  27. // Dump - dumps all logs into a formatted string
  28. func Dump() string {
  29. var dumpString = ""
  30. type keyVal struct {
  31. Key string
  32. Value time.Time
  33. }
  34. var mu sync.Mutex
  35. mu.Lock()
  36. defer mu.Unlock()
  37. var dumpLogs = make([]keyVal, 0, len(currentLogs))
  38. for key, value := range currentLogs {
  39. parsedTime, err := time.Parse(TimeFormat, value)
  40. if err == nil {
  41. dumpLogs = append(dumpLogs, keyVal{
  42. Key: key,
  43. Value: parsedTime,
  44. })
  45. }
  46. }
  47. sort.Slice(dumpLogs, func(i, j int) bool {
  48. return dumpLogs[i].Value.Before(dumpLogs[j].Value)
  49. })
  50. for i := range dumpLogs {
  51. var currLog = dumpLogs[i]
  52. dumpString += MakeString(" ", "[netmaker]", currLog.Value.Format(TimeFormat), currLog.Key, "\n")
  53. }
  54. resetLogs()
  55. return dumpString
  56. }
  57. // DumpFile - appends log dump log file
  58. func DumpFile(filePath string) {
  59. f, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
  60. if err != nil {
  61. fmt.Println(MakeString(" ", "could not open log file", filePath))
  62. return
  63. }
  64. defer f.Close()
  65. if _, err = f.WriteString(Dump()); err != nil {
  66. fmt.Println("could not dump logs")
  67. }
  68. }
  69. // Retrieve - retrieves logs from given file
  70. func Retrieve(filePath string) string {
  71. contents, err := os.ReadFile(filePath)
  72. if err != nil {
  73. panic(err)
  74. }
  75. return string(contents)
  76. }
  77. // FatalLog - exits os after logging
  78. func FatalLog(message ...string) {
  79. var mu sync.Mutex
  80. mu.Lock()
  81. defer mu.Unlock()
  82. fmt.Printf("[netmaker] Fatal: %s \n", MakeString(" ", message...))
  83. os.Exit(2)
  84. }
  85. // == private ==
  86. // resetLogs - reallocates logs map
  87. func resetLogs() {
  88. currentLogs = make(map[string]string)
  89. }