entry.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. newEntry.Logger.mu.Unlock()
  195. if reportCaller {
  196. newEntry.Caller = getCaller()
  197. }
  198. newEntry.fireHooks()
  199. buffer = getBuffer()
  200. defer func() {
  201. newEntry.Buffer = nil
  202. putBuffer(buffer)
  203. }()
  204. buffer.Reset()
  205. newEntry.Buffer = buffer
  206. newEntry.write()
  207. newEntry.Buffer = nil
  208. // To avoid Entry#log() returning a value that only would make sense for
  209. // panic() to use in Entry#Panic(), we avoid the allocation by checking
  210. // directly here.
  211. if level <= PanicLevel {
  212. panic(newEntry)
  213. }
  214. }
  215. func (entry *Entry) fireHooks() {
  216. var tmpHooks LevelHooks
  217. entry.Logger.mu.Lock()
  218. tmpHooks = make(LevelHooks, len(entry.Logger.Hooks))
  219. for k, v := range entry.Logger.Hooks {
  220. tmpHooks[k] = v
  221. }
  222. entry.Logger.mu.Unlock()
  223. err := tmpHooks.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. serialized, err := entry.Logger.Formatter.Format(entry)
  230. if err != nil {
  231. fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
  232. return
  233. }
  234. entry.Logger.mu.Lock()
  235. defer entry.Logger.mu.Unlock()
  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. }
  273. // Entry Printf family functions
  274. func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
  275. if entry.Logger.IsLevelEnabled(level) {
  276. entry.Log(level, fmt.Sprintf(format, args...))
  277. }
  278. }
  279. func (entry *Entry) Tracef(format string, args ...interface{}) {
  280. entry.Logf(TraceLevel, format, args...)
  281. }
  282. func (entry *Entry) Debugf(format string, args ...interface{}) {
  283. entry.Logf(DebugLevel, format, args...)
  284. }
  285. func (entry *Entry) Infof(format string, args ...interface{}) {
  286. entry.Logf(InfoLevel, format, args...)
  287. }
  288. func (entry *Entry) Printf(format string, args ...interface{}) {
  289. entry.Infof(format, args...)
  290. }
  291. func (entry *Entry) Warnf(format string, args ...interface{}) {
  292. entry.Logf(WarnLevel, format, args...)
  293. }
  294. func (entry *Entry) Warningf(format string, args ...interface{}) {
  295. entry.Warnf(format, args...)
  296. }
  297. func (entry *Entry) Errorf(format string, args ...interface{}) {
  298. entry.Logf(ErrorLevel, format, args...)
  299. }
  300. func (entry *Entry) Fatalf(format string, args ...interface{}) {
  301. entry.Logf(FatalLevel, format, args...)
  302. entry.Logger.Exit(1)
  303. }
  304. func (entry *Entry) Panicf(format string, args ...interface{}) {
  305. entry.Logf(PanicLevel, format, args...)
  306. }
  307. // Entry Println family functions
  308. func (entry *Entry) Logln(level Level, args ...interface{}) {
  309. if entry.Logger.IsLevelEnabled(level) {
  310. entry.Log(level, entry.sprintlnn(args...))
  311. }
  312. }
  313. func (entry *Entry) Traceln(args ...interface{}) {
  314. entry.Logln(TraceLevel, args...)
  315. }
  316. func (entry *Entry) Debugln(args ...interface{}) {
  317. entry.Logln(DebugLevel, args...)
  318. }
  319. func (entry *Entry) Infoln(args ...interface{}) {
  320. entry.Logln(InfoLevel, args...)
  321. }
  322. func (entry *Entry) Println(args ...interface{}) {
  323. entry.Infoln(args...)
  324. }
  325. func (entry *Entry) Warnln(args ...interface{}) {
  326. entry.Logln(WarnLevel, args...)
  327. }
  328. func (entry *Entry) Warningln(args ...interface{}) {
  329. entry.Warnln(args...)
  330. }
  331. func (entry *Entry) Errorln(args ...interface{}) {
  332. entry.Logln(ErrorLevel, args...)
  333. }
  334. func (entry *Entry) Fatalln(args ...interface{}) {
  335. entry.Logln(FatalLevel, args...)
  336. entry.Logger.Exit(1)
  337. }
  338. func (entry *Entry) Panicln(args ...interface{}) {
  339. entry.Logln(PanicLevel, args...)
  340. }
  341. // Sprintlnn => Sprint no newline. This is to get the behavior of how
  342. // fmt.Sprintln where spaces are always added between operands, regardless of
  343. // their type. Instead of vendoring the Sprintln implementation to spare a
  344. // string allocation, we do the simplest thing.
  345. func (entry *Entry) sprintlnn(args ...interface{}) string {
  346. msg := fmt.Sprintln(args...)
  347. return msg[:len(msg)-1]
  348. }