entry.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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
  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. } else {
  214. _, err = entry.Logger.Out.Write(serialized)
  215. if err != nil {
  216. fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
  217. }
  218. }
  219. }
  220. func (entry *Entry) Log(level Level, args ...interface{}) {
  221. if entry.Logger.IsLevelEnabled(level) {
  222. entry.log(level, fmt.Sprint(args...))
  223. }
  224. }
  225. func (entry *Entry) Trace(args ...interface{}) {
  226. entry.Log(TraceLevel, args...)
  227. }
  228. func (entry *Entry) Debug(args ...interface{}) {
  229. entry.Log(DebugLevel, args...)
  230. }
  231. func (entry *Entry) Print(args ...interface{}) {
  232. entry.Info(args...)
  233. }
  234. func (entry *Entry) Info(args ...interface{}) {
  235. entry.Log(InfoLevel, args...)
  236. }
  237. func (entry *Entry) Warn(args ...interface{}) {
  238. entry.Log(WarnLevel, args...)
  239. }
  240. func (entry *Entry) Warning(args ...interface{}) {
  241. entry.Warn(args...)
  242. }
  243. func (entry *Entry) Error(args ...interface{}) {
  244. entry.Log(ErrorLevel, args...)
  245. }
  246. func (entry *Entry) Fatal(args ...interface{}) {
  247. entry.Log(FatalLevel, args...)
  248. entry.Logger.Exit(1)
  249. }
  250. func (entry *Entry) Panic(args ...interface{}) {
  251. entry.Log(PanicLevel, args...)
  252. panic(fmt.Sprint(args...))
  253. }
  254. // Entry Printf family functions
  255. func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
  256. if entry.Logger.IsLevelEnabled(level) {
  257. entry.Log(level, fmt.Sprintf(format, args...))
  258. }
  259. }
  260. func (entry *Entry) Tracef(format string, args ...interface{}) {
  261. entry.Logf(TraceLevel, format, args...)
  262. }
  263. func (entry *Entry) Debugf(format string, args ...interface{}) {
  264. entry.Logf(DebugLevel, format, args...)
  265. }
  266. func (entry *Entry) Infof(format string, args ...interface{}) {
  267. entry.Logf(InfoLevel, format, args...)
  268. }
  269. func (entry *Entry) Printf(format string, args ...interface{}) {
  270. entry.Infof(format, args...)
  271. }
  272. func (entry *Entry) Warnf(format string, args ...interface{}) {
  273. entry.Logf(WarnLevel, format, args...)
  274. }
  275. func (entry *Entry) Warningf(format string, args ...interface{}) {
  276. entry.Warnf(format, args...)
  277. }
  278. func (entry *Entry) Errorf(format string, args ...interface{}) {
  279. entry.Logf(ErrorLevel, format, args...)
  280. }
  281. func (entry *Entry) Fatalf(format string, args ...interface{}) {
  282. entry.Logf(FatalLevel, format, args...)
  283. entry.Logger.Exit(1)
  284. }
  285. func (entry *Entry) Panicf(format string, args ...interface{}) {
  286. entry.Logf(PanicLevel, format, args...)
  287. }
  288. // Entry Println family functions
  289. func (entry *Entry) Logln(level Level, args ...interface{}) {
  290. if entry.Logger.IsLevelEnabled(level) {
  291. entry.Log(level, entry.sprintlnn(args...))
  292. }
  293. }
  294. func (entry *Entry) Traceln(args ...interface{}) {
  295. entry.Logln(TraceLevel, args...)
  296. }
  297. func (entry *Entry) Debugln(args ...interface{}) {
  298. entry.Logln(DebugLevel, args...)
  299. }
  300. func (entry *Entry) Infoln(args ...interface{}) {
  301. entry.Logln(InfoLevel, args...)
  302. }
  303. func (entry *Entry) Println(args ...interface{}) {
  304. entry.Infoln(args...)
  305. }
  306. func (entry *Entry) Warnln(args ...interface{}) {
  307. entry.Logln(WarnLevel, args...)
  308. }
  309. func (entry *Entry) Warningln(args ...interface{}) {
  310. entry.Warnln(args...)
  311. }
  312. func (entry *Entry) Errorln(args ...interface{}) {
  313. entry.Logln(ErrorLevel, args...)
  314. }
  315. func (entry *Entry) Fatalln(args ...interface{}) {
  316. entry.Logln(FatalLevel, args...)
  317. entry.Logger.Exit(1)
  318. }
  319. func (entry *Entry) Panicln(args ...interface{}) {
  320. entry.Logln(PanicLevel, args...)
  321. }
  322. // Sprintlnn => Sprint no newline. This is to get the behavior of how
  323. // fmt.Sprintln where spaces are always added between operands, regardless of
  324. // their type. Instead of vendoring the Sprintln implementation to spare a
  325. // string allocation, we do the simplest thing.
  326. func (entry *Entry) sprintlnn(args ...interface{}) string {
  327. msg := fmt.Sprintln(args...)
  328. return msg[:len(msg)-1]
  329. }