entry.go 11 KB

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