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