另客网go项目公用的代码库

entry.go 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. fieldErr := entry.err
  90. for k, v := range fields {
  91. isErrField := false
  92. if t := reflect.TypeOf(v); t != nil {
  93. switch t.Kind() {
  94. case reflect.Func:
  95. isErrField = true
  96. case reflect.Ptr:
  97. isErrField = t.Elem().Kind() == reflect.Func
  98. }
  99. }
  100. if isErrField {
  101. tmp := fmt.Sprintf("can not add field %q", k)
  102. if fieldErr != "" {
  103. fieldErr = entry.err + ", " + tmp
  104. } else {
  105. fieldErr = tmp
  106. }
  107. } else {
  108. data[k] = v
  109. }
  110. }
  111. return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr}
  112. }
  113. // Overrides the time of the Entry.
  114. func (entry *Entry) WithTime(t time.Time) *Entry {
  115. return &Entry{Logger: entry.Logger, Data: entry.Data, Time: t, err: entry.err}
  116. }
  117. // getPackageName reduces a fully qualified function name to the package name
  118. // There really ought to be to be a better way...
  119. func getPackageName(f string) string {
  120. for {
  121. lastPeriod := strings.LastIndex(f, ".")
  122. lastSlash := strings.LastIndex(f, "/")
  123. if lastPeriod > lastSlash {
  124. f = f[:lastPeriod]
  125. } else {
  126. break
  127. }
  128. }
  129. return f
  130. }
  131. // getCaller retrieves the name of the first non-logrus calling function
  132. func getCaller() *runtime.Frame {
  133. // Restrict the lookback frames to avoid runaway lookups
  134. pcs := make([]uintptr, maximumCallerDepth)
  135. depth := runtime.Callers(minimumCallerDepth, pcs)
  136. frames := runtime.CallersFrames(pcs[:depth])
  137. // cache this package's fully-qualified name
  138. callerInitOnce.Do(func() {
  139. logrusPackage = getPackageName(runtime.FuncForPC(pcs[0]).Name())
  140. // now that we have the cache, we can skip a minimum count of known-logrus functions
  141. // XXX this is dubious, the number of frames may vary store an entry in a logger interface
  142. minimumCallerDepth = knownLogrusFrames
  143. })
  144. for f, again := frames.Next(); again; f, again = frames.Next() {
  145. pkg := getPackageName(f.Function)
  146. // If the caller isn't part of this package, we're done
  147. if pkg != logrusPackage {
  148. return &f
  149. }
  150. }
  151. // if we got here, we failed to find the caller's context
  152. return nil
  153. }
  154. func (entry Entry) HasCaller() (has bool) {
  155. return entry.Logger != nil &&
  156. entry.Logger.ReportCaller &&
  157. entry.Caller != nil
  158. }
  159. // This function is not declared with a pointer value because otherwise
  160. // race conditions will occur when using multiple goroutines
  161. func (entry Entry) log(level Level, msg string) {
  162. var buffer *bytes.Buffer
  163. // Default to now, but allow users to override if they want.
  164. //
  165. // We don't have to worry about polluting future calls to Entry#log()
  166. // with this assignment because this function is declared with a
  167. // non-pointer receiver.
  168. if entry.Time.IsZero() {
  169. entry.Time = time.Now()
  170. }
  171. entry.Level = level
  172. entry.Message = msg
  173. if entry.Logger.ReportCaller {
  174. entry.Caller = getCaller()
  175. }
  176. entry.fireHooks()
  177. buffer = bufferPool.Get().(*bytes.Buffer)
  178. buffer.Reset()
  179. defer bufferPool.Put(buffer)
  180. entry.Buffer = buffer
  181. entry.write()
  182. entry.Buffer = nil
  183. // To avoid Entry#log() returning a value that only would make sense for
  184. // panic() to use in Entry#Panic(), we avoid the allocation by checking
  185. // directly here.
  186. if level <= PanicLevel {
  187. panic(&entry)
  188. }
  189. }
  190. func (entry *Entry) fireHooks() {
  191. entry.Logger.mu.Lock()
  192. defer entry.Logger.mu.Unlock()
  193. err := entry.Logger.Hooks.Fire(entry.Level, entry)
  194. if err != nil {
  195. fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
  196. }
  197. }
  198. func (entry *Entry) write() {
  199. entry.Logger.mu.Lock()
  200. defer entry.Logger.mu.Unlock()
  201. serialized, err := entry.Logger.Formatter.Format(entry)
  202. if err != nil {
  203. fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
  204. } else {
  205. _, err = entry.Logger.Out.Write(serialized)
  206. if err != nil {
  207. fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
  208. }
  209. }
  210. }
  211. func (entry *Entry) Log(level Level, args ...interface{}) {
  212. if entry.Logger.IsLevelEnabled(level) {
  213. entry.log(level, fmt.Sprint(args...))
  214. }
  215. }
  216. func (entry *Entry) Trace(args ...interface{}) {
  217. entry.Log(TraceLevel, args...)
  218. }
  219. func (entry *Entry) Debug(args ...interface{}) {
  220. entry.Log(DebugLevel, args...)
  221. }
  222. func (entry *Entry) Print(args ...interface{}) {
  223. entry.Info(args...)
  224. }
  225. func (entry *Entry) Info(args ...interface{}) {
  226. entry.Log(InfoLevel, args...)
  227. }
  228. func (entry *Entry) Warn(args ...interface{}) {
  229. entry.Log(WarnLevel, args...)
  230. }
  231. func (entry *Entry) Warning(args ...interface{}) {
  232. entry.Warn(args...)
  233. }
  234. func (entry *Entry) Error(args ...interface{}) {
  235. entry.Log(ErrorLevel, args...)
  236. }
  237. func (entry *Entry) Fatal(args ...interface{}) {
  238. entry.Log(FatalLevel, args...)
  239. entry.Logger.Exit(1)
  240. }
  241. func (entry *Entry) Panic(args ...interface{}) {
  242. entry.Log(PanicLevel, args...)
  243. panic(fmt.Sprint(args...))
  244. }
  245. // Entry Printf family functions
  246. func (entry *Entry) Logf(level Level, format string, args ...interface{}) {
  247. entry.Log(level, fmt.Sprintf(format, args...))
  248. }
  249. func (entry *Entry) Tracef(format string, args ...interface{}) {
  250. entry.Logf(TraceLevel, format, args...)
  251. }
  252. func (entry *Entry) Debugf(format string, args ...interface{}) {
  253. entry.Logf(DebugLevel, format, args...)
  254. }
  255. func (entry *Entry) Infof(format string, args ...interface{}) {
  256. entry.Logf(InfoLevel, format, args...)
  257. }
  258. func (entry *Entry) Printf(format string, args ...interface{}) {
  259. entry.Infof(format, args...)
  260. }
  261. func (entry *Entry) Warnf(format string, args ...interface{}) {
  262. entry.Logf(WarnLevel, format, args...)
  263. }
  264. func (entry *Entry) Warningf(format string, args ...interface{}) {
  265. entry.Warnf(format, args...)
  266. }
  267. func (entry *Entry) Errorf(format string, args ...interface{}) {
  268. entry.Logf(ErrorLevel, format, args...)
  269. }
  270. func (entry *Entry) Fatalf(format string, args ...interface{}) {
  271. entry.Logf(FatalLevel, format, args...)
  272. entry.Logger.Exit(1)
  273. }
  274. func (entry *Entry) Panicf(format string, args ...interface{}) {
  275. entry.Logf(PanicLevel, format, args...)
  276. }
  277. // Entry Println family functions
  278. func (entry *Entry) Logln(level Level, args ...interface{}) {
  279. if entry.Logger.IsLevelEnabled(level) {
  280. entry.Log(level, entry.sprintlnn(args...))
  281. }
  282. }
  283. func (entry *Entry) Traceln(args ...interface{}) {
  284. entry.Logln(TraceLevel, args...)
  285. }
  286. func (entry *Entry) Debugln(args ...interface{}) {
  287. entry.Logln(DebugLevel, args...)
  288. }
  289. func (entry *Entry) Infoln(args ...interface{}) {
  290. entry.Logln(InfoLevel, args...)
  291. }
  292. func (entry *Entry) Println(args ...interface{}) {
  293. entry.Infoln(args...)
  294. }
  295. func (entry *Entry) Warnln(args ...interface{}) {
  296. entry.Logln(WarnLevel, args...)
  297. }
  298. func (entry *Entry) Warningln(args ...interface{}) {
  299. entry.Warnln(args...)
  300. }
  301. func (entry *Entry) Errorln(args ...interface{}) {
  302. entry.Logln(ErrorLevel, args...)
  303. }
  304. func (entry *Entry) Fatalln(args ...interface{}) {
  305. entry.Logln(FatalLevel, args...)
  306. entry.Logger.Exit(1)
  307. }
  308. func (entry *Entry) Panicln(args ...interface{}) {
  309. entry.Logln(PanicLevel, args...)
  310. }
  311. // Sprintlnn => Sprint no newline. This is to get the behavior of how
  312. // fmt.Sprintln where spaces are always added between operands, regardless of
  313. // their type. Instead of vendoring the Sprintln implementation to spare a
  314. // string allocation, we do the simplest thing.
  315. func (entry *Entry) sprintlnn(args ...interface{}) string {
  316. msg := fmt.Sprintln(args...)
  317. return msg[:len(msg)-1]
  318. }