default.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. package logger
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "os"
  7. "runtime"
  8. "sort"
  9. "strings"
  10. "sync"
  11. "time"
  12. dlog "IotAdmin/core/debug/log"
  13. )
  14. func init() {
  15. lvl, err := GetLevel(os.Getenv("IOT_ADMIN_LOG_LEVEL"))
  16. if err != nil {
  17. lvl = InfoLevel
  18. }
  19. DefaultLogger = NewHelper(NewLogger(WithLevel(lvl)))
  20. }
  21. type defaultLogger struct {
  22. sync.RWMutex
  23. opts Options
  24. }
  25. // Init (opts...) should only overwrite provided options
  26. func (l *defaultLogger) Init(opts ...Option) error {
  27. for _, o := range opts {
  28. o(&l.opts)
  29. }
  30. return nil
  31. }
  32. func (l *defaultLogger) String() string {
  33. return "default"
  34. }
  35. func (l *defaultLogger) Fields(fields map[string]interface{}) Logger {
  36. l.Lock()
  37. l.opts.Fields = copyFields(fields)
  38. l.Unlock()
  39. return l
  40. }
  41. // logCallerFilePath 返回调用程序的package/file:line描述,只保留叶目录名和文件名。
  42. func logCallerFilePath(loggingFilePath string) string {
  43. // To make sure we trim the path correctly on Windows too, we
  44. // counter-intuitively need to use '/' and *not* os.PathSeparator here,
  45. // because the path given originates from Go stdlib, specifically
  46. // runtime.Caller() which (as of Mar/17) returns forward slashes even on
  47. // Windows.
  48. //
  49. // See https://github.com/golang/go/issues/3335
  50. // and https://github.com/golang/go/issues/18151
  51. //
  52. // for discussion on the issue on Go side.
  53. idx := strings.LastIndexByte(loggingFilePath, '/')
  54. if idx == -1 {
  55. return loggingFilePath
  56. }
  57. idx = strings.LastIndexByte(loggingFilePath[:idx], '/')
  58. if idx == -1 {
  59. return loggingFilePath
  60. }
  61. return loggingFilePath[idx+1:]
  62. }
  63. func (l *defaultLogger) Log(level Level, v ...interface{}) {
  64. l.logf(level, "", v...)
  65. }
  66. func (l *defaultLogger) Logf(level Level, format string, v ...interface{}) {
  67. l.logf(level, format, v...)
  68. }
  69. func (l *defaultLogger) logf(level Level, format string, v ...interface{}) {
  70. // TODO decide does we need to write message if log level not used?
  71. if !l.opts.Level.Enabled(level) {
  72. return
  73. }
  74. l.RLock()
  75. fields := copyFields(l.opts.Fields)
  76. l.RUnlock()
  77. rec := dlog.Record{
  78. Timestamp: time.Now(),
  79. Metadata: make(map[string]string, len(fields)),
  80. }
  81. //s := "[" + rec.Timestamp.Format("2006-01-02 15:04:05.000Z0700")
  82. str := "[" + rec.Timestamp.Format("2006-01-02 15:04:05.000")
  83. if l.opts.Name != "" {
  84. str += " " + l.opts.Name
  85. }
  86. str += "][" + strings.ToUpper(level.String()) + "]"
  87. if _, file, line, ok := runtime.Caller(l.opts.CallerSkipCount); ok && level.String() == "error" {
  88. str += "[ERR:" + fmt.Sprintf("%s:%d", logCallerFilePath(file), line) + "]"
  89. }
  90. if format == "" {
  91. rec.Message = fmt.Sprint(v...)
  92. } else {
  93. rec.Message = fmt.Sprintf(format, v...)
  94. }
  95. keys := make([]string, 0, len(fields))
  96. for k, v := range fields {
  97. keys = append(keys, k)
  98. rec.Metadata[k] = fmt.Sprintf("%v", v)
  99. }
  100. sort.Strings(keys)
  101. metadata := ""
  102. for i, k := range keys {
  103. if i == 0 {
  104. metadata += fmt.Sprintf("%v", fields[k])
  105. } else {
  106. metadata += fmt.Sprintf(" %v", fields[k])
  107. }
  108. }
  109. logStr := fmt.Sprintf("%s %s %v\n", str, metadata, rec.Message)
  110. _, err := l.opts.Out.Write([]byte(logStr))
  111. if err != nil {
  112. log.Printf("log [Logf] write error: %s \n", err.Error())
  113. }
  114. }
  115. func (l *defaultLogger) Options() Options {
  116. // not guard against options Context values
  117. l.RLock()
  118. opts := l.opts
  119. opts.Fields = copyFields(l.opts.Fields)
  120. l.RUnlock()
  121. return opts
  122. }
  123. // NewLogger builds a new logger based on options
  124. func NewLogger(opts ...Option) Logger {
  125. // Default options
  126. options := Options{
  127. Level: InfoLevel,
  128. Fields: make(map[string]interface{}),
  129. Out: os.Stderr,
  130. CallerSkipCount: 3,
  131. Context: context.Background(),
  132. Name: "",
  133. }
  134. l := &defaultLogger{opts: options}
  135. if err := l.Init(opts...); err != nil {
  136. l.Log(FatalLevel, err)
  137. }
  138. return l
  139. }