You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

279 lines
6.8 KiB

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