entry.go 10 KB

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