entry.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. package logrus
  2. import (
  3. "bytes"
  4. "context"
  5. "fmt"
  6. "os"
  7. "reflect"
  8. "runtime"
  9. "strings"
  10. "sync"
  11. "time"
  12. )
  13. var (
  14. bufferPool *sync.Pool
  15. // qualified package name, cached at first use
  16. logrusPackage string
  17. // Positions in the call stack when tracing to report the calling method
  18. minimumCallerDepth int
  19. // Used for caller information initialisation
  20. callerInitOnce sync.Once
  21. )
  22. const (
  23. maximumCallerDepth int = 25
  24. knownLogrusFrames int = 4
  25. )
  26. func init() {
  27. bufferPool = &sync.Pool{
  28. New: func() interface{} {
  29. return new(bytes.Buffer)
  30. },
  31. }
  32. // start at the bottom of the stack before the package-name cache is primed
  33. minimumCallerDepth = 1
  34. }
  35. // Defines the key when adding errors using WithError.
  36. var ErrorKey = "error"
  37. // An entry is the final or intermediate Logrus logging entry. It contains all
  38. // the fields passed with WithField{,s}. It's finally logged when Trace, Debug,
  39. // Info, Warn, Error, Fatal or Panic is called on it. These objects can be
  40. // reused and passed around as much as you wish to avoid field duplication.
  41. type Entry struct {
  42. Logger *Logger
  43. // Contains all the fields set by the user.
  44. Data Fields
  45. // Time at which the log entry was created
  46. Time time.Time
  47. // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic
  48. // This field will be set on entry firing and the value will be equal to the one in Logger struct field.
  49. Level Level
  50. // Calling method, with package name
  51. Caller *runtime.Frame
  52. // Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic
  53. Message string
  54. // When formatter is called in entry.log(), a Buffer may be set to entry
  55. Buffer *bytes.Buffer
  56. // Contains the context set by the user. Useful for hook processing etc.
  57. Context context.Context
  58. // err may contain a field formatting error
  59. err string
  60. }
  61. func NewEntry(logger *Logger) *Entry {
  62. return &Entry{
  63. Logger: logger,
  64. // Default is three fields, plus one optional. Give a little extra room.
  65. Data: make(Fields, 6),
  66. }
  67. }
  68. // Returns the string representation from the reader and ultimately the
  69. // formatter.
  70. func (entry *Entry) String() (string, error) {
  71. serialized, err := entry.Logger.Formatter.Format(entry)
  72. if err != nil {
  73. return "", err
  74. }
  75. str := string(serialized)
  76. return str, nil
  77. }
  78. // Add an error as single field (using the key defined in ErrorKey) to the Entry.
  79. func (entry *Entry) WithError(err error) *Entry {
  80. return entry.WithField(ErrorKey, err)
  81. }
  82. // Add a context to the Entry.
  83. func (entry *Entry) WithContext(ctx context.Context) *Entry {
  84. return &Entry{Logger: entry.Logger, Data: entry.Data, Time: entry.Time, err: entry.err, Context: ctx}
  85. }
  86. // Add a single field to the Entry.
  87. func (entry *Entry) WithField(key string, value interface{}) *Entry {
  88. return entry.WithFields(Fields{key: value})
  89. }
  90. // Add a map of fields to the Entry.
  91. func (entry *Entry) WithFields(fields Fields) *Entry {
  92. data := make(Fields, len(entry.Data)+len(fields))
  93. for k, v := range entry.Data {
  94. data[k] = v
  95. }
  96. fieldErr := entry.err
  97. for k, v := range fields {
  98. isErrField := false
  99. if t := reflect.TypeOf(v); t != nil {
  100. switch t.Kind() {
  101. case reflect.Func:
  102. isErrField = true
  103. case reflect.Ptr:
  104. isErrField = t.Elem().Kind() == reflect.Func
  105. }
  106. }
  107. if isErrField {
  108. tmp := fmt.Sprintf("can not add field %q", k)
  109. if fieldErr != "" {
  110. fieldErr = entry.err + ", " + tmp
  111. } else {
  112. fieldErr = tmp
  113. }
  114. } else {
  115. data[k] = v
  116. }
  117. }
  118. return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context}
  119. }
  120. // Overrides the time of the Entry.
  121. func (entry *Entry) WithTime(t time.Time) *Entry {
  122. return &Entry{Logger: entry.Logger, Data: entry.Data, Time: t, err: entry.err, Context: entry.Context}
  123. }
  124. // getPackageName reduces a fully qualified function name to the package name
  125. // There really ought to be to be a better way...
  126. func getPackageName(f string) string {
  127. for {
  128. lastPeriod := strings.LastIndex(f, ".")
  129. lastSlash := strings.LastIndex(f, "/")
  130. if lastPeriod > lastSlash {
  131. f = f[:lastPeriod]
  132. } else {
  133. break
  134. }
  135. }
  136. return f
  137. }
  138. // getCaller retrieves the name of the first non-logrus calling function
  139. func getCaller() *runtime.Frame {
  140. // cache this package's fully-qualified name
  141. callerInitOnce.Do(func() {
  142. pcs := make([]uintptr, 2)
  143. _ = runtime.Callers(0, pcs)
  144. logrusPackage = getPackageName(runtime.FuncForPC(pcs[1]).Name())
  145. // now that we have the cache, we can skip a minimum count of known-logrus functions
  146. // XXX this is dubious, the number of frames may vary
  147. minimumCallerDepth = knownLogrusFrames
  148. })
  149. // Restrict the lookback frames to avoid runaway lookups
  150. pcs := make([]uintptr, maximumCallerDepth)
  151. depth := runtime.Callers(minimumCallerDepth, pcs)
  152. frames := runtime.CallersFrames(pcs[:depth])
  153. for f, again := frames.Next(); again; f, again = frames.Next() {
  154. pkg := getPackageName(f.Function)
  155. // If the caller isn't part of this package, we're done
  156. if pkg != logrusPackage {
  157. return &f //nolint:scopelint
  158. }
  159. }
  160. // if we got here, we failed to find the caller's context
  161. return nil
  162. }
  163. func (entry Entry) HasCaller() (has bool) {
  164. return entry.Logger != nil &&
  165. entry.Logger.ReportCaller &&
  166. entry.Caller != nil
  167. }
  168. // This function is not declared with a pointer value because otherwise
  169. // race conditions will occur when using multiple goroutines
  170. func (entry Entry) log(level Level, msg string) {
  171. var buffer *bytes.Buffer
  172. // Default to now, but allow users to override if they want.
  173. //
  174. // We don't have to worry about polluting future calls to Entry#log()
  175. // with this assignment because this function is declared with a
  176. // non-pointer receiver.
  177. if entry.Time.IsZero() {
  178. entry.Time = time.Now()
  179. }
  180. entry.Level = level
  181. entry.Message = msg
  182. if entry.Logger.ReportCaller {
  183. entry.Caller = getCaller()
  184. }
  185. entry.fireHooks()
  186. buffer = bufferPool.Get().(*bytes.Buffer)
  187. buffer.Reset()
  188. defer bufferPool.Put(buffer)
  189. entry.Buffer = buffer
  190. entry.write()
  191. entry.Buffer = nil
  192. // To avoid Entry#log() returning a value that only would make sense for
  193. // panic() to use in Entry#Panic(), we avoid the allocation by checking
  194. // directly here.
  195. if level <= PanicLevel {
  196. panic(&entry)
  197. }
  198. }
  199. func (entry *Entry) fireHooks() {
  200. entry.Logger.mu.Lock()
  201. defer entry.Logger.mu.Unlock()
  202. err := entry.Logger.Hooks.Fire(entry.Level, entry)
  203. if err != nil {
  204. fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
  205. }
  206. }
  207. func (entry *Entry) write() {
  208. entry.Logger.mu.Lock()
  209. defer entry.Logger.mu.Unlock()
  210. serialized, err := entry.Logger.Formatter.Format(entry)
  211. if err != nil {
  212. fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
  213. return
  214. }
  215. if _, err = entry.Logger.Out.Write(serialized); err != nil {
  216. fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
  217. }
  218. }
  219. func (entry *Entry) Log(level Level, args ...interface{}) {
  220. if entry.Logger.IsLevelEnabled(level) {
  221. entry.log(level, fmt.Sprint(args...))
  222. }
  223. }
  224. func (entry *Entry) Trace(args ...interface{}) {
  225. entry.Log(TraceLevel, args...)
  226. }
  227. func (entry *Entry) Debug(args ...interface{}) {
  228. entry.Log(DebugLevel, args...)
  229. }
  230. func (entry *Entry) Print(args ...interface{}) {
  231. entry.Info(args...)
  232. }
  233. func (entry *Entry) Info(args ...interface{}) {
  234. entry.Log(InfoLevel, args...)
  235. }
  236. func (entry *Entry) Warn(args ...interface{}) {
  237. entry.Log(WarnLevel, args...)
  238. }
  239. func (entry *Entry) Warning(args ...interface{}) {
  240. entry.Warn(args...)
  241. }
  242. func (entry *Entry) Error(args ...interface{}) {
  243. entry.Log(ErrorLevel, args...)
  244. }
  245. func (entry *Entry) Fatal(args ...interface{}) {
  246. entry.Log(FatalLevel, args...)
  247. entry.Logger.Exit(1)
  248. }
  249. func (entry *Entry) Panic(args ...interface{}) {
  250. entry.Log(PanicLevel, args...)
  251. panic(fmt.Sprint(args...))
  252. }
  253. // Entry Printf family functions
  254. func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
  255. if entry.Logger.IsLevelEnabled(level) {
  256. entry.Log(level, fmt.Sprintf(format, args...))
  257. }
  258. }
  259. func (entry *Entry) Tracef(format string, args ...interface{}) {
  260. entry.Logf(TraceLevel, format, args...)
  261. }
  262. func (entry *Entry) Debugf(format string, args ...interface{}) {
  263. entry.Logf(DebugLevel, format, args...)
  264. }
  265. func (entry *Entry) Infof(format string, args ...interface{}) {
  266. entry.Logf(InfoLevel, format, args...)
  267. }
  268. func (entry *Entry) Printf(format string, args ...interface{}) {
  269. entry.Infof(format, args...)
  270. }
  271. func (entry *Entry) Warnf(format string, args ...interface{}) {
  272. entry.Logf(WarnLevel, format, args...)
  273. }
  274. func (entry *Entry) Warningf(format string, args ...interface{}) {
  275. entry.Warnf(format, args...)
  276. }
  277. func (entry *Entry) Errorf(format string, args ...interface{}) {
  278. entry.Logf(ErrorLevel, format, args...)
  279. }
  280. func (entry *Entry) Fatalf(format string, args ...interface{}) {
  281. entry.Logf(FatalLevel, format, args...)
  282. entry.Logger.Exit(1)
  283. }
  284. func (entry *Entry) Panicf(format string, args ...interface{}) {
  285. entry.Logf(PanicLevel, format, args...)
  286. }
  287. // Entry Println family functions
  288. func (entry *Entry) Logln(level Level, args ...interface{}) {
  289. if entry.Logger.IsLevelEnabled(level) {
  290. entry.Log(level, entry.sprintlnn(args...))
  291. }
  292. }
  293. func (entry *Entry) Traceln(args ...interface{}) {
  294. entry.Logln(TraceLevel, args...)
  295. }
  296. func (entry *Entry) Debugln(args ...interface{}) {
  297. entry.Logln(DebugLevel, args...)
  298. }
  299. func (entry *Entry) Infoln(args ...interface{}) {
  300. entry.Logln(InfoLevel, args...)
  301. }
  302. func (entry *Entry) Println(args ...interface{}) {
  303. entry.Infoln(args...)
  304. }
  305. func (entry *Entry) Warnln(args ...interface{}) {
  306. entry.Logln(WarnLevel, args...)
  307. }
  308. func (entry *Entry) Warningln(args ...interface{}) {
  309. entry.Warnln(args...)
  310. }
  311. func (entry *Entry) Errorln(args ...interface{}) {
  312. entry.Logln(ErrorLevel, args...)
  313. }
  314. func (entry *Entry) Fatalln(args ...interface{}) {
  315. entry.Logln(FatalLevel, args...)
  316. entry.Logger.Exit(1)
  317. }
  318. func (entry *Entry) Panicln(args ...interface{}) {
  319. entry.Logln(PanicLevel, args...)
  320. }
  321. // Sprintlnn => Sprint no newline. This is to get the behavior of how
  322. // fmt.Sprintln where spaces are always added between operands, regardless of
  323. // their type. Instead of vendoring the Sprintln implementation to spare a
  324. // string allocation, we do the simplest thing.
  325. func (entry *Entry) sprintlnn(args ...interface{}) string {
  326. msg := fmt.Sprintln(args...)
  327. return msg[:len(msg)-1]
  328. }