default.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. fields["level"] = level.String()
  78. if _, file, line, ok := runtime.Caller(l.opts.CallerSkipCount); ok && level.String() == "error" {
  79. fields["file"] = fmt.Sprintf("%s:%d", logCallerFilePath(file), line)
  80. }
  81. rec := dlog.Record{
  82. Timestamp: time.Now(),
  83. Metadata: make(map[string]string, len(fields)),
  84. }
  85. if format == "" {
  86. rec.Message = fmt.Sprint(v...)
  87. } else {
  88. rec.Message = fmt.Sprintf(format, v...)
  89. }
  90. keys := make([]string, 0, len(fields))
  91. for k, v := range fields {
  92. keys = append(keys, k)
  93. rec.Metadata[k] = fmt.Sprintf("%v", v)
  94. }
  95. sort.Strings(keys)
  96. metadata := ""
  97. for i, k := range keys {
  98. if i == 0 {
  99. metadata += fmt.Sprintf("%v", fields[k])
  100. } else {
  101. metadata += fmt.Sprintf(" %v", fields[k])
  102. }
  103. }
  104. var name string
  105. if l.opts.Name != "" {
  106. name = "[" + l.opts.Name + "]"
  107. }
  108. t := rec.Timestamp.Format("2006-01-02 15:04:05.000Z0700")
  109. //fmt.Printf("%s\n", t)
  110. //fmt.Printf("%s\n", name)
  111. //fmt.Printf("%s\n", metadata)
  112. //fmt.Printf("%v\n", rec.Message)
  113. logStr := ""
  114. if name == "" {
  115. logStr = fmt.Sprintf("%s %s %v\n", t, metadata, rec.Message)
  116. } else {
  117. logStr = fmt.Sprintf("%s %s %s %v\n", name, t, metadata, rec.Message)
  118. }
  119. _, err := l.opts.Out.Write([]byte(logStr))
  120. if err != nil {
  121. log.Printf("log [Logf] write error: %s \n", err.Error())
  122. }
  123. }
  124. func (l *defaultLogger) Options() Options {
  125. // not guard against options Context values
  126. l.RLock()
  127. opts := l.opts
  128. opts.Fields = copyFields(l.opts.Fields)
  129. l.RUnlock()
  130. return opts
  131. }
  132. // NewLogger builds a new logger based on options
  133. func NewLogger(opts ...Option) Logger {
  134. // Default options
  135. options := Options{
  136. Level: InfoLevel,
  137. Fields: make(map[string]interface{}),
  138. Out: os.Stderr,
  139. CallerSkipCount: 3,
  140. Context: context.Background(),
  141. Name: "",
  142. }
  143. l := &defaultLogger{opts: options}
  144. if err := l.Init(opts...); err != nil {
  145. l.Log(FatalLevel, err)
  146. }
  147. return l
  148. }