logger.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package log
  2. import (
  3. "fmt"
  4. "os"
  5. "time"
  6. "github.com/go-stack/stack"
  7. )
  8. const timeKey = "t"
  9. const lvlKey = "lvl"
  10. const msgKey = "msg"
  11. const ctxKey = "ctx"
  12. const errorKey = "LOG15_ERROR"
  13. const skipLevel = 2
  14. type Lvl int
  15. const (
  16. LvlCrit Lvl = iota
  17. LvlError
  18. LvlWarn
  19. LvlInfo
  20. LvlDebug
  21. LvlTrace
  22. )
  23. // AlignedString returns a 5-character string containing the name of a Lvl.
  24. func (l Lvl) AlignedString() string {
  25. switch l {
  26. case LvlTrace:
  27. return "TRACE"
  28. case LvlDebug:
  29. return "DEBUG"
  30. case LvlInfo:
  31. return "INFO "
  32. case LvlWarn:
  33. return "WARN "
  34. case LvlError:
  35. return "ERROR"
  36. case LvlCrit:
  37. return "CRIT "
  38. default:
  39. panic("bad level")
  40. }
  41. }
  42. // Strings returns the name of a Lvl.
  43. func (l Lvl) String() string {
  44. switch l {
  45. case LvlTrace:
  46. return "trce"
  47. case LvlDebug:
  48. return "dbug"
  49. case LvlInfo:
  50. return "info"
  51. case LvlWarn:
  52. return "warn"
  53. case LvlError:
  54. return "eror"
  55. case LvlCrit:
  56. return "crit"
  57. default:
  58. panic("bad level")
  59. }
  60. }
  61. // LvlFromString returns the appropriate Lvl from a string name.
  62. // Useful for parsing command line args and configuration files.
  63. func LvlFromString(lvlString string) (Lvl, error) {
  64. switch lvlString {
  65. case "trace", "trce":
  66. return LvlTrace, nil
  67. case "debug", "dbug":
  68. return LvlDebug, nil
  69. case "info":
  70. return LvlInfo, nil
  71. case "warn":
  72. return LvlWarn, nil
  73. case "error", "eror":
  74. return LvlError, nil
  75. case "crit":
  76. return LvlCrit, nil
  77. default:
  78. return LvlDebug, fmt.Errorf("unknown level: %v", lvlString)
  79. }
  80. }
  81. // A Record is what a Logger asks its handler to write
  82. type Record struct {
  83. Time time.Time
  84. Lvl Lvl
  85. Msg string
  86. Ctx []interface{}
  87. Call stack.Call
  88. KeyNames RecordKeyNames
  89. }
  90. // RecordKeyNames gets stored in a Record when the write function is executed.
  91. type RecordKeyNames struct {
  92. Time string
  93. Msg string
  94. Lvl string
  95. Ctx string
  96. }
  97. // A Logger writes key/value pairs to a Handler
  98. type Logger interface {
  99. // New returns a new Logger that has this logger's context plus the given context
  100. New(ctx ...interface{}) Logger
  101. // GetHandler gets the handler associated with the logger.
  102. GetHandler() Handler
  103. // SetHandler updates the logger to write records to the specified handler.
  104. SetHandler(h Handler)
  105. // Log a message at the given level with context key/value pairs
  106. Trace(msg string, ctx ...interface{})
  107. Debug(msg string, ctx ...interface{})
  108. Info(msg string, ctx ...interface{})
  109. Warn(msg string, ctx ...interface{})
  110. Error(msg string, ctx ...interface{})
  111. Crit(msg string, ctx ...interface{})
  112. }
  113. type logger struct {
  114. ctx []interface{}
  115. h *swapHandler
  116. }
  117. func (l *logger) write(msg string, lvl Lvl, ctx []interface{}, skip int) {
  118. l.h.Log(&Record{
  119. Time: time.Now(),
  120. Lvl: lvl,
  121. Msg: msg,
  122. Ctx: newContext(l.ctx, ctx),
  123. Call: stack.Caller(skip),
  124. KeyNames: RecordKeyNames{
  125. Time: timeKey,
  126. Msg: msgKey,
  127. Lvl: lvlKey,
  128. Ctx: ctxKey,
  129. },
  130. })
  131. }
  132. func (l *logger) New(ctx ...interface{}) Logger {
  133. child := &logger{newContext(l.ctx, ctx), new(swapHandler)}
  134. child.SetHandler(l.h)
  135. return child
  136. }
  137. func newContext(prefix []interface{}, suffix []interface{}) []interface{} {
  138. normalizedSuffix := normalize(suffix)
  139. newCtx := make([]interface{}, len(prefix)+len(normalizedSuffix))
  140. n := copy(newCtx, prefix)
  141. copy(newCtx[n:], normalizedSuffix)
  142. return newCtx
  143. }
  144. func (l *logger) Trace(msg string, ctx ...interface{}) {
  145. l.write(msg, LvlTrace, ctx, skipLevel)
  146. }
  147. func (l *logger) Debug(msg string, ctx ...interface{}) {
  148. l.write(msg, LvlDebug, ctx, skipLevel)
  149. }
  150. func (l *logger) Info(msg string, ctx ...interface{}) {
  151. l.write(msg, LvlInfo, ctx, skipLevel)
  152. }
  153. func (l *logger) Warn(msg string, ctx ...interface{}) {
  154. l.write(msg, LvlWarn, ctx, skipLevel)
  155. }
  156. func (l *logger) Error(msg string, ctx ...interface{}) {
  157. l.write(msg, LvlError, ctx, skipLevel)
  158. }
  159. func (l *logger) Crit(msg string, ctx ...interface{}) {
  160. l.write(msg, LvlCrit, ctx, skipLevel)
  161. os.Exit(1)
  162. }
  163. func (l *logger) GetHandler() Handler {
  164. return l.h.Get()
  165. }
  166. func (l *logger) SetHandler(h Handler) {
  167. l.h.Swap(h)
  168. }
  169. func normalize(ctx []interface{}) []interface{} {
  170. // if the caller passed a Ctx object, then expand it
  171. if len(ctx) == 1 {
  172. if ctxMap, ok := ctx[0].(Ctx); ok {
  173. ctx = ctxMap.toArray()
  174. }
  175. }
  176. // ctx needs to be even because it's a series of key/value pairs
  177. // no one wants to check for errors on logging functions,
  178. // so instead of erroring on bad input, we'll just make sure
  179. // that things are the right length and users can fix bugs
  180. // when they see the output looks wrong
  181. if len(ctx)%2 != 0 {
  182. ctx = append(ctx, nil, errorKey, "Normalized odd number of arguments by adding nil")
  183. }
  184. return ctx
  185. }
  186. // Lazy allows you to defer calculation of a logged value that is expensive
  187. // to compute until it is certain that it must be evaluated with the given filters.
  188. //
  189. // Lazy may also be used in conjunction with a Logger's New() function
  190. // to generate a child logger which always reports the current value of changing
  191. // state.
  192. //
  193. // You may wrap any function which takes no arguments to Lazy. It may return any
  194. // number of values of any type.
  195. type Lazy struct {
  196. Fn interface{}
  197. }
  198. // Ctx is a map of key/value pairs to pass as context to a log function
  199. // Use this only if you really need greater safety around the arguments you pass
  200. // to the logging functions.
  201. type Ctx map[string]interface{}
  202. func (c Ctx) toArray() []interface{} {
  203. arr := make([]interface{}, len(c)*2)
  204. i := 0
  205. for k, v := range c {
  206. arr[i] = k
  207. arr[i+1] = v
  208. i += 2
  209. }
  210. return arr
  211. }