entry.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // Copyright (c) 2016 Uber Technologies, Inc.
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. package zapcore
  21. import (
  22. "fmt"
  23. "strings"
  24. "sync"
  25. "time"
  26. "go.uber.org/zap/internal/bufferpool"
  27. "go.uber.org/zap/internal/exit"
  28. "go.uber.org/multierr"
  29. )
  30. var (
  31. _cePool = sync.Pool{New: func() interface{} {
  32. // Pre-allocate some space for cores.
  33. return &CheckedEntry{
  34. cores: make([]Core, 4),
  35. }
  36. }}
  37. )
  38. func getCheckedEntry() *CheckedEntry {
  39. ce := _cePool.Get().(*CheckedEntry)
  40. ce.reset()
  41. return ce
  42. }
  43. func putCheckedEntry(ce *CheckedEntry) {
  44. if ce == nil {
  45. return
  46. }
  47. _cePool.Put(ce)
  48. }
  49. // NewEntryCaller makes an EntryCaller from the return signature of
  50. // runtime.Caller.
  51. func NewEntryCaller(pc uintptr, file string, line int, ok bool) EntryCaller {
  52. if !ok {
  53. return EntryCaller{}
  54. }
  55. return EntryCaller{
  56. PC: pc,
  57. File: file,
  58. Line: line,
  59. Defined: true,
  60. }
  61. }
  62. // EntryCaller represents the caller of a logging function.
  63. type EntryCaller struct {
  64. Defined bool
  65. PC uintptr
  66. File string
  67. Line int
  68. }
  69. // String returns the full path and line number of the caller.
  70. func (ec EntryCaller) String() string {
  71. return ec.FullPath()
  72. }
  73. // FullPath returns a /full/path/to/package/file:line description of the
  74. // caller.
  75. func (ec EntryCaller) FullPath() string {
  76. if !ec.Defined {
  77. return "undefined"
  78. }
  79. buf := bufferpool.Get()
  80. buf.AppendString(ec.File)
  81. buf.AppendByte(':')
  82. buf.AppendInt(int64(ec.Line))
  83. caller := buf.String()
  84. buf.Free()
  85. return caller
  86. }
  87. // TrimmedPath returns a package/file:line description of the caller,
  88. // preserving only the leaf directory name and file name.
  89. func (ec EntryCaller) TrimmedPath() string {
  90. if !ec.Defined {
  91. return "undefined"
  92. }
  93. // nb. To make sure we trim the path correctly on Windows too, we
  94. // counter-intuitively need to use '/' and *not* os.PathSeparator here,
  95. // because the path given originates from Go stdlib, specifically
  96. // runtime.Caller() which (as of Mar/17) returns forward slashes even on
  97. // Windows.
  98. //
  99. // See https://github.com/golang/go/issues/3335
  100. // and https://github.com/golang/go/issues/18151
  101. //
  102. // for discussion on the issue on Go side.
  103. //
  104. // Find the last separator.
  105. //
  106. idx := strings.LastIndexByte(ec.File, '/')
  107. if idx == -1 {
  108. return ec.FullPath()
  109. }
  110. // Find the penultimate separator.
  111. idx = strings.LastIndexByte(ec.File[:idx], '/')
  112. if idx == -1 {
  113. return ec.FullPath()
  114. }
  115. buf := bufferpool.Get()
  116. // Keep everything after the penultimate separator.
  117. buf.AppendString(ec.File[idx+1:])
  118. buf.AppendByte(':')
  119. buf.AppendInt(int64(ec.Line))
  120. caller := buf.String()
  121. buf.Free()
  122. return caller
  123. }
  124. // An Entry represents a complete log message. The entry's structured context
  125. // is already serialized, but the log level, time, message, and call site
  126. // information are available for inspection and modification. Any fields left
  127. // empty will be omitted when encoding.
  128. //
  129. // Entries are pooled, so any functions that accept them MUST be careful not to
  130. // retain references to them.
  131. type Entry struct {
  132. Level Level
  133. Time time.Time
  134. LoggerName string
  135. Message string
  136. Caller EntryCaller
  137. Stack string
  138. }
  139. // CheckWriteAction indicates what action to take after a log entry is
  140. // processed. Actions are ordered in increasing severity.
  141. type CheckWriteAction uint8
  142. const (
  143. // WriteThenNoop indicates that nothing special needs to be done. It's the
  144. // default behavior.
  145. WriteThenNoop CheckWriteAction = iota
  146. // WriteThenPanic causes a panic after Write.
  147. WriteThenPanic
  148. // WriteThenFatal causes a fatal os.Exit after Write.
  149. WriteThenFatal
  150. )
  151. // CheckedEntry is an Entry together with a collection of Cores that have
  152. // already agreed to log it.
  153. //
  154. // CheckedEntry references should be created by calling AddCore or Should on a
  155. // nil *CheckedEntry. References are returned to a pool after Write, and MUST
  156. // NOT be retained after calling their Write method.
  157. type CheckedEntry struct {
  158. Entry
  159. ErrorOutput WriteSyncer
  160. dirty bool // best-effort detection of pool misuse
  161. should CheckWriteAction
  162. cores []Core
  163. }
  164. func (ce *CheckedEntry) reset() {
  165. ce.Entry = Entry{}
  166. ce.ErrorOutput = nil
  167. ce.dirty = false
  168. ce.should = WriteThenNoop
  169. for i := range ce.cores {
  170. // don't keep references to cores
  171. ce.cores[i] = nil
  172. }
  173. ce.cores = ce.cores[:0]
  174. }
  175. // Write writes the entry to the stored Cores, returns any errors, and returns
  176. // the CheckedEntry reference to a pool for immediate re-use. Finally, it
  177. // executes any required CheckWriteAction.
  178. func (ce *CheckedEntry) Write(fields ...Field) {
  179. if ce == nil {
  180. return
  181. }
  182. if ce.dirty {
  183. if ce.ErrorOutput != nil {
  184. // Make a best effort to detect unsafe re-use of this CheckedEntry.
  185. // If the entry is dirty, log an internal error; because the
  186. // CheckedEntry is being used after it was returned to the pool,
  187. // the message may be an amalgamation from multiple call sites.
  188. fmt.Fprintf(ce.ErrorOutput, "%v Unsafe CheckedEntry re-use near Entry %+v.\n", time.Now(), ce.Entry)
  189. ce.ErrorOutput.Sync()
  190. }
  191. return
  192. }
  193. ce.dirty = true
  194. var err error
  195. for i := range ce.cores {
  196. err = multierr.Append(err, ce.cores[i].Write(ce.Entry, fields))
  197. }
  198. if ce.ErrorOutput != nil {
  199. if err != nil {
  200. fmt.Fprintf(ce.ErrorOutput, "%v write error: %v\n", time.Now(), err)
  201. ce.ErrorOutput.Sync()
  202. }
  203. }
  204. should, msg := ce.should, ce.Message
  205. putCheckedEntry(ce)
  206. switch should {
  207. case WriteThenPanic:
  208. panic(msg)
  209. case WriteThenFatal:
  210. exit.Exit()
  211. }
  212. }
  213. // AddCore adds a Core that has agreed to log this CheckedEntry. It's intended to be
  214. // used by Core.Check implementations, and is safe to call on nil CheckedEntry
  215. // references.
  216. func (ce *CheckedEntry) AddCore(ent Entry, core Core) *CheckedEntry {
  217. if ce == nil {
  218. ce = getCheckedEntry()
  219. ce.Entry = ent
  220. }
  221. ce.cores = append(ce.cores, core)
  222. return ce
  223. }
  224. // Should sets this CheckedEntry's CheckWriteAction, which controls whether a
  225. // Core will panic or fatal after writing this log entry. Like AddCore, it's
  226. // safe to call on nil CheckedEntry references.
  227. func (ce *CheckedEntry) Should(ent Entry, should CheckWriteAction) *CheckedEntry {
  228. if ce == nil {
  229. ce = getCheckedEntry()
  230. ce.Entry = ent
  231. }
  232. ce.should = should
  233. return ce
  234. }