entry.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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 five 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. entry.fireHooks()
  81. buffer = bufferPool.Get().(*bytes.Buffer)
  82. buffer.Reset()
  83. defer bufferPool.Put(buffer)
  84. entry.Buffer = buffer
  85. entry.write()
  86. entry.Buffer = nil
  87. // To avoid Entry#log() returning a value that only would make sense for
  88. // panic() to use in Entry#Panic(), we avoid the allocation by checking
  89. // directly here.
  90. if level <= PanicLevel {
  91. panic(&entry)
  92. }
  93. }
  94. // This function is not declared with a pointer value because otherwise
  95. // race conditions will occur when using multiple goroutines
  96. func (entry Entry) fireHooks() {
  97. entry.Logger.mu.Lock()
  98. defer entry.Logger.mu.Unlock()
  99. err := entry.Logger.Hooks.Fire(entry.Level, &entry)
  100. if err != nil {
  101. fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
  102. }
  103. }
  104. func (entry *Entry) write() {
  105. serialized, err := entry.Logger.Formatter.Format(entry)
  106. entry.Logger.mu.Lock()
  107. defer entry.Logger.mu.Unlock()
  108. if err != nil {
  109. fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
  110. } else {
  111. _, err = entry.Logger.Out.Write(serialized)
  112. if err != nil {
  113. fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
  114. }
  115. }
  116. }
  117. func (entry *Entry) Debug(args ...interface{}) {
  118. if entry.Logger.level() >= DebugLevel {
  119. entry.log(DebugLevel, fmt.Sprint(args...))
  120. }
  121. }
  122. func (entry *Entry) Print(args ...interface{}) {
  123. entry.Info(args...)
  124. }
  125. func (entry *Entry) Info(args ...interface{}) {
  126. if entry.Logger.level() >= InfoLevel {
  127. entry.log(InfoLevel, fmt.Sprint(args...))
  128. }
  129. }
  130. func (entry *Entry) Warn(args ...interface{}) {
  131. if entry.Logger.level() >= WarnLevel {
  132. entry.log(WarnLevel, fmt.Sprint(args...))
  133. }
  134. }
  135. func (entry *Entry) Warning(args ...interface{}) {
  136. entry.Warn(args...)
  137. }
  138. func (entry *Entry) Error(args ...interface{}) {
  139. if entry.Logger.level() >= ErrorLevel {
  140. entry.log(ErrorLevel, fmt.Sprint(args...))
  141. }
  142. }
  143. func (entry *Entry) Fatal(args ...interface{}) {
  144. if entry.Logger.level() >= FatalLevel {
  145. entry.log(FatalLevel, fmt.Sprint(args...))
  146. }
  147. Exit(1)
  148. }
  149. func (entry *Entry) Panic(args ...interface{}) {
  150. if entry.Logger.level() >= PanicLevel {
  151. entry.log(PanicLevel, fmt.Sprint(args...))
  152. }
  153. panic(fmt.Sprint(args...))
  154. }
  155. // Entry Printf family functions
  156. func (entry *Entry) Debugf(format string, args ...interface{}) {
  157. if entry.Logger.level() >= DebugLevel {
  158. entry.Debug(fmt.Sprintf(format, args...))
  159. }
  160. }
  161. func (entry *Entry) Infof(format string, args ...interface{}) {
  162. if entry.Logger.level() >= InfoLevel {
  163. entry.Info(fmt.Sprintf(format, args...))
  164. }
  165. }
  166. func (entry *Entry) Printf(format string, args ...interface{}) {
  167. entry.Infof(format, args...)
  168. }
  169. func (entry *Entry) Warnf(format string, args ...interface{}) {
  170. if entry.Logger.level() >= WarnLevel {
  171. entry.Warn(fmt.Sprintf(format, args...))
  172. }
  173. }
  174. func (entry *Entry) Warningf(format string, args ...interface{}) {
  175. entry.Warnf(format, args...)
  176. }
  177. func (entry *Entry) Errorf(format string, args ...interface{}) {
  178. if entry.Logger.level() >= ErrorLevel {
  179. entry.Error(fmt.Sprintf(format, args...))
  180. }
  181. }
  182. func (entry *Entry) Fatalf(format string, args ...interface{}) {
  183. if entry.Logger.level() >= FatalLevel {
  184. entry.Fatal(fmt.Sprintf(format, args...))
  185. }
  186. Exit(1)
  187. }
  188. func (entry *Entry) Panicf(format string, args ...interface{}) {
  189. if entry.Logger.level() >= PanicLevel {
  190. entry.Panic(fmt.Sprintf(format, args...))
  191. }
  192. }
  193. // Entry Println family functions
  194. func (entry *Entry) Debugln(args ...interface{}) {
  195. if entry.Logger.level() >= DebugLevel {
  196. entry.Debug(entry.sprintlnn(args...))
  197. }
  198. }
  199. func (entry *Entry) Infoln(args ...interface{}) {
  200. if entry.Logger.level() >= InfoLevel {
  201. entry.Info(entry.sprintlnn(args...))
  202. }
  203. }
  204. func (entry *Entry) Println(args ...interface{}) {
  205. entry.Infoln(args...)
  206. }
  207. func (entry *Entry) Warnln(args ...interface{}) {
  208. if entry.Logger.level() >= WarnLevel {
  209. entry.Warn(entry.sprintlnn(args...))
  210. }
  211. }
  212. func (entry *Entry) Warningln(args ...interface{}) {
  213. entry.Warnln(args...)
  214. }
  215. func (entry *Entry) Errorln(args ...interface{}) {
  216. if entry.Logger.level() >= ErrorLevel {
  217. entry.Error(entry.sprintlnn(args...))
  218. }
  219. }
  220. func (entry *Entry) Fatalln(args ...interface{}) {
  221. if entry.Logger.level() >= FatalLevel {
  222. entry.Fatal(entry.sprintlnn(args...))
  223. }
  224. Exit(1)
  225. }
  226. func (entry *Entry) Panicln(args ...interface{}) {
  227. if entry.Logger.level() >= PanicLevel {
  228. entry.Panic(entry.sprintlnn(args...))
  229. }
  230. }
  231. // Sprintlnn => Sprint no newline. This is to get the behavior of how
  232. // fmt.Sprintln where spaces are always added between operands, regardless of
  233. // their type. Instead of vendoring the Sprintln implementation to spare a
  234. // string allocation, we do the simplest thing.
  235. func (entry *Entry) sprintlnn(args ...interface{}) string {
  236. msg := fmt.Sprintln(args...)
  237. return msg[:len(msg)-1]
  238. }