entry.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 bytes representation of this entry from the formatter.
  69. func (entry *Entry) Bytes() ([]byte, error) {
  70. return entry.Logger.Formatter.Format(entry)
  71. }
  72. // Returns the string representation from the reader and ultimately the
  73. // formatter.
  74. func (entry *Entry) String() (string, error) {
  75. serialized, err := entry.Bytes()
  76. if err != nil {
  77. return "", err
  78. }
  79. str := string(serialized)
  80. return str, nil
  81. }
  82. // Add an error as single field (using the key defined in ErrorKey) to the Entry.
  83. func (entry *Entry) WithError(err error) *Entry {
  84. return entry.WithField(ErrorKey, err)
  85. }
  86. // Add a context to the Entry.
  87. func (entry *Entry) WithContext(ctx context.Context) *Entry {
  88. dataCopy := make(Fields, len(entry.Data))
  89. for k, v := range entry.Data {
  90. dataCopy[k] = v
  91. }
  92. return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx}
  93. }
  94. // Add a single field to the Entry.
  95. func (entry *Entry) WithField(key string, value interface{}) *Entry {
  96. return entry.WithFields(Fields{key: value})
  97. }
  98. // Add a map of fields to the Entry.
  99. func (entry *Entry) WithFields(fields Fields) *Entry {
  100. entry.Logger.mu.Lock()
  101. defer entry.Logger.mu.Unlock()
  102. data := make(Fields, len(entry.Data)+len(fields))
  103. for k, v := range entry.Data {
  104. data[k] = v
  105. }
  106. fieldErr := entry.err
  107. for k, v := range fields {
  108. isErrField := false
  109. if t := reflect.TypeOf(v); t != nil {
  110. switch t.Kind() {
  111. case reflect.Func:
  112. isErrField = true
  113. case reflect.Ptr:
  114. isErrField = t.Elem().Kind() == reflect.Func
  115. }
  116. }
  117. if isErrField {
  118. tmp := fmt.Sprintf("can not add field %q", k)
  119. if fieldErr != "" {
  120. fieldErr = entry.err + ", " + tmp
  121. } else {
  122. fieldErr = tmp
  123. }
  124. } else {
  125. data[k] = v
  126. }
  127. }
  128. return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context}
  129. }
  130. // Overrides the time of the Entry.
  131. func (entry *Entry) WithTime(t time.Time) *Entry {
  132. dataCopy := make(Fields, len(entry.Data))
  133. for k, v := range entry.Data {
  134. dataCopy[k] = v
  135. }
  136. return &Entry{Logger: entry.Logger, Data: dataCopy, Time: t, err: entry.err, Context: entry.Context}
  137. }
  138. // getPackageName reduces a fully qualified function name to the package name
  139. // There really ought to be to be a better way...
  140. func getPackageName(f string) string {
  141. for {
  142. lastPeriod := strings.LastIndex(f, ".")
  143. lastSlash := strings.LastIndex(f, "/")
  144. if lastPeriod > lastSlash {
  145. f = f[:lastPeriod]
  146. } else {
  147. break
  148. }
  149. }
  150. return f
  151. }
  152. // getCaller retrieves the name of the first non-logrus calling function
  153. func getCaller() *runtime.Frame {
  154. // cache this package's fully-qualified name
  155. callerInitOnce.Do(func() {
  156. pcs := make([]uintptr, maximumCallerDepth)
  157. _ = runtime.Callers(0, pcs)
  158. // dynamic get the package name and the minimum caller depth
  159. for i := 0; i < maximumCallerDepth; i++ {
  160. funcName := runtime.FuncForPC(pcs[i]).Name()
  161. if strings.Contains(funcName, "getCaller") {
  162. logrusPackage = getPackageName(funcName)
  163. break
  164. }
  165. }
  166. minimumCallerDepth = knownLogrusFrames
  167. })
  168. // Restrict the lookback frames to avoid runaway lookups
  169. pcs := make([]uintptr, maximumCallerDepth)
  170. depth := runtime.Callers(minimumCallerDepth, pcs)
  171. frames := runtime.CallersFrames(pcs[:depth])
  172. for f, again := frames.Next(); again; f, again = frames.Next() {
  173. pkg := getPackageName(f.Function)
  174. // If the caller isn't part of this package, we're done
  175. if pkg != logrusPackage {
  176. return &f //nolint:scopelint
  177. }
  178. }
  179. // if we got here, we failed to find the caller's context
  180. return nil
  181. }
  182. func (entry Entry) HasCaller() (has bool) {
  183. return entry.Logger != nil &&
  184. entry.Logger.ReportCaller &&
  185. entry.Caller != nil
  186. }
  187. // This function is not declared with a pointer value because otherwise
  188. // race conditions will occur when using multiple goroutines
  189. func (entry Entry) log(level Level, msg string) {
  190. var buffer *bytes.Buffer
  191. // Default to now, but allow users to override if they want.
  192. //
  193. // We don't have to worry about polluting future calls to Entry#log()
  194. // with this assignment because this function is declared with a
  195. // non-pointer receiver.
  196. if entry.Time.IsZero() {
  197. entry.Time = time.Now()
  198. }
  199. entry.Level = level
  200. entry.Message = msg
  201. entry.Logger.mu.Lock()
  202. if entry.Logger.ReportCaller {
  203. entry.Caller = getCaller()
  204. }
  205. entry.Logger.mu.Unlock()
  206. entry.fireHooks()
  207. buffer = bufferPool.Get().(*bytes.Buffer)
  208. buffer.Reset()
  209. defer bufferPool.Put(buffer)
  210. entry.Buffer = buffer
  211. entry.write()
  212. entry.Buffer = nil
  213. // To avoid Entry#log() returning a value that only would make sense for
  214. // panic() to use in Entry#Panic(), we avoid the allocation by checking
  215. // directly here.
  216. if level <= PanicLevel {
  217. panic(&entry)
  218. }
  219. }
  220. func (entry *Entry) fireHooks() {
  221. entry.Logger.mu.Lock()
  222. defer entry.Logger.mu.Unlock()
  223. err := entry.Logger.Hooks.Fire(entry.Level, entry)
  224. if err != nil {
  225. fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
  226. }
  227. }
  228. func (entry *Entry) write() {
  229. entry.Logger.mu.Lock()
  230. defer entry.Logger.mu.Unlock()
  231. serialized, err := entry.Logger.Formatter.Format(entry)
  232. if err != nil {
  233. fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
  234. return
  235. }
  236. if _, err = entry.Logger.Out.Write(serialized); err != nil {
  237. fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
  238. }
  239. }
  240. func (entry *Entry) Log(level Level, args ...interface{}) {
  241. if entry.Logger.IsLevelEnabled(level) {
  242. entry.log(level, fmt.Sprint(args...))
  243. }
  244. }
  245. func (entry *Entry) Trace(args ...interface{}) {
  246. entry.Log(TraceLevel, args...)
  247. }
  248. func (entry *Entry) Debug(args ...interface{}) {
  249. entry.Log(DebugLevel, args...)
  250. }
  251. func (entry *Entry) Print(args ...interface{}) {
  252. entry.Info(args...)
  253. }
  254. func (entry *Entry) Info(args ...interface{}) {
  255. entry.Log(InfoLevel, args...)
  256. }
  257. func (entry *Entry) Warn(args ...interface{}) {
  258. entry.Log(WarnLevel, args...)
  259. }
  260. func (entry *Entry) Warning(args ...interface{}) {
  261. entry.Warn(args...)
  262. }
  263. func (entry *Entry) Error(args ...interface{}) {
  264. entry.Log(ErrorLevel, args...)
  265. }
  266. func (entry *Entry) Fatal(args ...interface{}) {
  267. entry.Log(FatalLevel, args...)
  268. entry.Logger.Exit(1)
  269. }
  270. func (entry *Entry) Panic(args ...interface{}) {
  271. entry.Log(PanicLevel, args...)
  272. panic(fmt.Sprint(args...))
  273. }
  274. // Entry Printf family functions
  275. func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
  276. if entry.Logger.IsLevelEnabled(level) {
  277. entry.Log(level, fmt.Sprintf(format, args...))
  278. }
  279. }
  280. func (entry *Entry) Tracef(format string, args ...interface{}) {
  281. entry.Logf(TraceLevel, format, args...)
  282. }
  283. func (entry *Entry) Debugf(format string, args ...interface{}) {
  284. entry.Logf(DebugLevel, format, args...)
  285. }
  286. func (entry *Entry) Infof(format string, args ...interface{}) {
  287. entry.Logf(InfoLevel, format, args...)
  288. }
  289. func (entry *Entry) Printf(format string, args ...interface{}) {
  290. entry.Infof(format, args...)
  291. }
  292. func (entry *Entry) Warnf(format string, args ...interface{}) {
  293. entry.Logf(WarnLevel, format, args...)
  294. }
  295. func (entry *Entry) Warningf(format string, args ...interface{}) {
  296. entry.Warnf(format, args...)
  297. }
  298. func (entry *Entry) Errorf(format string, args ...interface{}) {
  299. entry.Logf(ErrorLevel, format, args...)
  300. }
  301. func (entry *Entry) Fatalf(format string, args ...interface{}) {
  302. entry.Logf(FatalLevel, format, args...)
  303. entry.Logger.Exit(1)
  304. }
  305. func (entry *Entry) Panicf(format string, args ...interface{}) {
  306. entry.Logf(PanicLevel, format, args...)
  307. }
  308. // Entry Println family functions
  309. func (entry *Entry) Logln(level Level, args ...interface{}) {
  310. if entry.Logger.IsLevelEnabled(level) {
  311. entry.Log(level, entry.sprintlnn(args...))
  312. }
  313. }
  314. func (entry *Entry) Traceln(args ...interface{}) {
  315. entry.Logln(TraceLevel, args...)
  316. }
  317. func (entry *Entry) Debugln(args ...interface{}) {
  318. entry.Logln(DebugLevel, args...)
  319. }
  320. func (entry *Entry) Infoln(args ...interface{}) {
  321. entry.Logln(InfoLevel, args...)
  322. }
  323. func (entry *Entry) Println(args ...interface{}) {
  324. entry.Infoln(args...)
  325. }
  326. func (entry *Entry) Warnln(args ...interface{}) {
  327. entry.Logln(WarnLevel, args...)
  328. }
  329. func (entry *Entry) Warningln(args ...interface{}) {
  330. entry.Warnln(args...)
  331. }
  332. func (entry *Entry) Errorln(args ...interface{}) {
  333. entry.Logln(ErrorLevel, args...)
  334. }
  335. func (entry *Entry) Fatalln(args ...interface{}) {
  336. entry.Logln(FatalLevel, args...)
  337. entry.Logger.Exit(1)
  338. }
  339. func (entry *Entry) Panicln(args ...interface{}) {
  340. entry.Logln(PanicLevel, args...)
  341. }
  342. // Sprintlnn => Sprint no newline. This is to get the behavior of how
  343. // fmt.Sprintln where spaces are always added between operands, regardless of
  344. // their type. Instead of vendoring the Sprintln implementation to spare a
  345. // string allocation, we do the simplest thing.
  346. func (entry *Entry) sprintlnn(args ...interface{}) string {
  347. msg := fmt.Sprintln(args...)
  348. return msg[:len(msg)-1]
  349. }