entry.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package logrus
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "sync"
  7. "time"
  8. )
  9. var bufferPool *sync.Pool
  10. func init() {
  11. bufferPool = &sync.Pool{
  12. New: func() interface{} {
  13. return new(bytes.Buffer)
  14. },
  15. }
  16. }
  17. // Defines the key when adding errors using WithError.
  18. var ErrorKey = "error"
  19. // An entry is the final or intermediate Logrus logging entry. It contains all
  20. // the fields passed with WithField{,s}. It's finally logged when Debug, Info,
  21. // Warn, Error, Fatal or Panic is called on it. These objects can be reused and
  22. // passed around as much as you wish to avoid field duplication.
  23. type Entry struct {
  24. Logger *Logger
  25. // Contains all the fields set by the user.
  26. Data Fields
  27. // Time at which the log entry was created
  28. Time time.Time
  29. // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
  30. Level Level
  31. // Message passed to Debug, Info, Warn, Error, Fatal or Panic
  32. Message string
  33. // When formatter is called in entry.log(), an Buffer may be set to entry
  34. Buffer *bytes.Buffer
  35. }
  36. func NewEntry(logger *Logger) *Entry {
  37. return &Entry{
  38. Logger: logger,
  39. // Default is three fields, give a little extra room
  40. Data: make(Fields, 5),
  41. }
  42. }
  43. // Returns the string representation from the reader and ultimately the
  44. // formatter.
  45. func (entry *Entry) String() (string, error) {
  46. serialized, err := entry.Logger.Formatter.Format(entry)
  47. if err != nil {
  48. return "", err
  49. }
  50. str := string(serialized)
  51. return str, nil
  52. }
  53. // Add an error as single field (using the key defined in ErrorKey) to the Entry.
  54. func (entry *Entry) WithError(err error) *Entry {
  55. return entry.WithField(ErrorKey, err)
  56. }
  57. // Add a single field to the Entry.
  58. func (entry *Entry) WithField(key string, value interface{}) *Entry {
  59. return entry.WithFields(Fields{key: value})
  60. }
  61. // Add a map of fields to the Entry.
  62. func (entry *Entry) WithFields(fields Fields) *Entry {
  63. data := make(Fields, len(entry.Data)+len(fields))
  64. for k, v := range entry.Data {
  65. data[k] = v
  66. }
  67. for k, v := range fields {
  68. data[k] = v
  69. }
  70. return &Entry{Logger: entry.Logger, Data: data}
  71. }
  72. // This function is not declared with a pointer value because otherwise
  73. // race conditions will occur when using multiple goroutines
  74. func (entry Entry) log(level Level, msg string) {
  75. var buffer *bytes.Buffer
  76. entry.Time = time.Now()
  77. entry.Level = level
  78. entry.Message = msg
  79. if err := entry.Logger.Hooks.Fire(level, &entry); err != nil {
  80. entry.Logger.mu.Lock()
  81. fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
  82. entry.Logger.mu.Unlock()
  83. }
  84. buffer = bufferPool.Get().(*bytes.Buffer)
  85. buffer.Reset()
  86. defer bufferPool.Put(buffer)
  87. entry.Buffer = buffer
  88. serialized, err := entry.Logger.Formatter.Format(&entry)
  89. entry.Buffer = nil
  90. if err != nil {
  91. entry.Logger.mu.Lock()
  92. fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
  93. entry.Logger.mu.Unlock()
  94. } else {
  95. entry.Logger.mu.Lock()
  96. _, err = entry.Logger.Out.Write(serialized)
  97. if err != nil {
  98. fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
  99. }
  100. entry.Logger.mu.Unlock()
  101. }
  102. // To avoid Entry#log() returning a value that only would make sense for
  103. // panic() to use in Entry#Panic(), we avoid the allocation by checking
  104. // directly here.
  105. if level <= PanicLevel {
  106. panic(&entry)
  107. }
  108. }
  109. func (entry *Entry) Debug(args ...interface{}) {
  110. if entry.Logger.Level >= DebugLevel {
  111. entry.log(DebugLevel, fmt.Sprint(args...))
  112. }
  113. }
  114. func (entry *Entry) Print(args ...interface{}) {
  115. entry.Info(args...)
  116. }
  117. func (entry *Entry) Info(args ...interface{}) {
  118. if entry.Logger.Level >= InfoLevel {
  119. entry.log(InfoLevel, fmt.Sprint(args...))
  120. }
  121. }
  122. func (entry *Entry) Warn(args ...interface{}) {
  123. if entry.Logger.Level >= WarnLevel {
  124. entry.log(WarnLevel, fmt.Sprint(args...))
  125. }
  126. }
  127. func (entry *Entry) Warning(args ...interface{}) {
  128. entry.Warn(args...)
  129. }
  130. func (entry *Entry) Error(args ...interface{}) {
  131. if entry.Logger.Level >= ErrorLevel {
  132. entry.log(ErrorLevel, fmt.Sprint(args...))
  133. }
  134. }
  135. func (entry *Entry) Fatal(args ...interface{}) {
  136. if entry.Logger.Level >= FatalLevel {
  137. entry.log(FatalLevel, fmt.Sprint(args...))
  138. }
  139. Exit(1)
  140. }
  141. func (entry *Entry) Panic(args ...interface{}) {
  142. if entry.Logger.Level >= PanicLevel {
  143. entry.log(PanicLevel, fmt.Sprint(args...))
  144. }
  145. panic(fmt.Sprint(args...))
  146. }
  147. // Entry Printf family functions
  148. func (entry *Entry) Debugf(format string, args ...interface{}) {
  149. if entry.Logger.Level >= DebugLevel {
  150. entry.Debug(fmt.Sprintf(format, args...))
  151. }
  152. }
  153. func (entry *Entry) Infof(format string, args ...interface{}) {
  154. if entry.Logger.Level >= InfoLevel {
  155. entry.Info(fmt.Sprintf(format, args...))
  156. }
  157. }
  158. func (entry *Entry) Printf(format string, args ...interface{}) {
  159. entry.Infof(format, args...)
  160. }
  161. func (entry *Entry) Warnf(format string, args ...interface{}) {
  162. if entry.Logger.Level >= WarnLevel {
  163. entry.Warn(fmt.Sprintf(format, args...))
  164. }
  165. }
  166. func (entry *Entry) Warningf(format string, args ...interface{}) {
  167. entry.Warnf(format, args...)
  168. }
  169. func (entry *Entry) Errorf(format string, args ...interface{}) {
  170. if entry.Logger.Level >= ErrorLevel {
  171. entry.Error(fmt.Sprintf(format, args...))
  172. }
  173. }
  174. func (entry *Entry) Fatalf(format string, args ...interface{}) {
  175. if entry.Logger.Level >= FatalLevel {
  176. entry.Fatal(fmt.Sprintf(format, args...))
  177. }
  178. Exit(1)
  179. }
  180. func (entry *Entry) Panicf(format string, args ...interface{}) {
  181. if entry.Logger.Level >= PanicLevel {
  182. entry.Panic(fmt.Sprintf(format, args...))
  183. }
  184. }
  185. // Entry Println family functions
  186. func (entry *Entry) Debugln(args ...interface{}) {
  187. if entry.Logger.Level >= DebugLevel {
  188. entry.Debug(entry.sprintlnn(args...))
  189. }
  190. }
  191. func (entry *Entry) Infoln(args ...interface{}) {
  192. if entry.Logger.Level >= InfoLevel {
  193. entry.Info(entry.sprintlnn(args...))
  194. }
  195. }
  196. func (entry *Entry) Println(args ...interface{}) {
  197. entry.Infoln(args...)
  198. }
  199. func (entry *Entry) Warnln(args ...interface{}) {
  200. if entry.Logger.Level >= WarnLevel {
  201. entry.Warn(entry.sprintlnn(args...))
  202. }
  203. }
  204. func (entry *Entry) Warningln(args ...interface{}) {
  205. entry.Warnln(args...)
  206. }
  207. func (entry *Entry) Errorln(args ...interface{}) {
  208. if entry.Logger.Level >= ErrorLevel {
  209. entry.Error(entry.sprintlnn(args...))
  210. }
  211. }
  212. func (entry *Entry) Fatalln(args ...interface{}) {
  213. if entry.Logger.Level >= FatalLevel {
  214. entry.Fatal(entry.sprintlnn(args...))
  215. }
  216. Exit(1)
  217. }
  218. func (entry *Entry) Panicln(args ...interface{}) {
  219. if entry.Logger.Level >= PanicLevel {
  220. entry.Panic(entry.sprintlnn(args...))
  221. }
  222. }
  223. // Sprintlnn => Sprint no newline. This is to get the behavior of how
  224. // fmt.Sprintln where spaces are always added between operands, regardless of
  225. // their type. Instead of vendoring the Sprintln implementation to spare a
  226. // string allocation, we do the simplest thing.
  227. func (entry *Entry) sprintlnn(args ...interface{}) string {
  228. msg := fmt.Sprintln(args...)
  229. return msg[:len(msg)-1]
  230. }