sampler.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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. "time"
  23. "go.uber.org/atomic"
  24. )
  25. const (
  26. _numLevels = _maxLevel - _minLevel + 1
  27. _countersPerLevel = 4096
  28. )
  29. type counter struct {
  30. resetAt atomic.Int64
  31. counter atomic.Uint64
  32. }
  33. type counters [_numLevels][_countersPerLevel]counter
  34. func newCounters() *counters {
  35. return &counters{}
  36. }
  37. func (cs *counters) get(lvl Level, key string) *counter {
  38. i := lvl - _minLevel
  39. j := fnv32a(key) % _countersPerLevel
  40. return &cs[i][j]
  41. }
  42. // fnv32a, adapted from "hash/fnv", but without a []byte(string) alloc
  43. func fnv32a(s string) uint32 {
  44. const (
  45. offset32 = 2166136261
  46. prime32 = 16777619
  47. )
  48. hash := uint32(offset32)
  49. for i := 0; i < len(s); i++ {
  50. hash ^= uint32(s[i])
  51. hash *= prime32
  52. }
  53. return hash
  54. }
  55. func (c *counter) IncCheckReset(t time.Time, tick time.Duration) uint64 {
  56. tn := t.UnixNano()
  57. resetAfter := c.resetAt.Load()
  58. if resetAfter > tn {
  59. return c.counter.Inc()
  60. }
  61. c.counter.Store(1)
  62. newResetAfter := tn + tick.Nanoseconds()
  63. if !c.resetAt.CAS(resetAfter, newResetAfter) {
  64. // We raced with another goroutine trying to reset, and it also reset
  65. // the counter to 1, so we need to reincrement the counter.
  66. return c.counter.Inc()
  67. }
  68. return 1
  69. }
  70. // SamplingDecision is a decision represented as a bit field made by sampler.
  71. // More decisions may be added in the future.
  72. type SamplingDecision uint32
  73. const (
  74. // LogDropped indicates that the Sampler dropped a log entry.
  75. LogDropped SamplingDecision = 1 << iota
  76. // LogSampled indicates that the Sampler sampled a log entry.
  77. LogSampled
  78. )
  79. // optionFunc wraps a func so it satisfies the SamplerOption interface.
  80. type optionFunc func(*sampler)
  81. func (f optionFunc) apply(s *sampler) {
  82. f(s)
  83. }
  84. // SamplerOption configures a Sampler.
  85. type SamplerOption interface {
  86. apply(*sampler)
  87. }
  88. // nopSamplingHook is the default hook used by sampler.
  89. func nopSamplingHook(Entry, SamplingDecision) {}
  90. // SamplerHook registers a function which will be called when Sampler makes a
  91. // decision.
  92. //
  93. // This hook may be used to get visibility into the performance of the sampler.
  94. // For example, use it to track metrics of dropped versus sampled logs.
  95. //
  96. // var dropped atomic.Int64
  97. // zapcore.SamplerHook(func(ent zapcore.Entry, dec zapcore.SamplingDecision) {
  98. // if dec&zapcore.LogDropped > 0 {
  99. // dropped.Inc()
  100. // }
  101. // })
  102. func SamplerHook(hook func(entry Entry, dec SamplingDecision)) SamplerOption {
  103. return optionFunc(func(s *sampler) {
  104. s.hook = hook
  105. })
  106. }
  107. // NewSamplerWithOptions creates a Core that samples incoming entries, which
  108. // caps the CPU and I/O load of logging while attempting to preserve a
  109. // representative subset of your logs.
  110. //
  111. // Zap samples by logging the first N entries with a given level and message
  112. // each tick. If more Entries with the same level and message are seen during
  113. // the same interval, every Mth message is logged and the rest are dropped.
  114. //
  115. // Sampler can be configured to report sampling decisions with the SamplerHook
  116. // option.
  117. //
  118. // Keep in mind that zap's sampling implementation is optimized for speed over
  119. // absolute precision; under load, each tick may be slightly over- or
  120. // under-sampled.
  121. func NewSamplerWithOptions(core Core, tick time.Duration, first, thereafter int, opts ...SamplerOption) Core {
  122. s := &sampler{
  123. Core: core,
  124. tick: tick,
  125. counts: newCounters(),
  126. first: uint64(first),
  127. thereafter: uint64(thereafter),
  128. hook: nopSamplingHook,
  129. }
  130. for _, opt := range opts {
  131. opt.apply(s)
  132. }
  133. return s
  134. }
  135. type sampler struct {
  136. Core
  137. counts *counters
  138. tick time.Duration
  139. first, thereafter uint64
  140. hook func(Entry, SamplingDecision)
  141. }
  142. // NewSampler creates a Core that samples incoming entries, which
  143. // caps the CPU and I/O load of logging while attempting to preserve a
  144. // representative subset of your logs.
  145. //
  146. // Zap samples by logging the first N entries with a given level and message
  147. // each tick. If more Entries with the same level and message are seen during
  148. // the same interval, every Mth message is logged and the rest are dropped.
  149. //
  150. // Keep in mind that zap's sampling implementation is optimized for speed over
  151. // absolute precision; under load, each tick may be slightly over- or
  152. // under-sampled.
  153. //
  154. // Deprecated: use NewSamplerWithOptions.
  155. func NewSampler(core Core, tick time.Duration, first, thereafter int) Core {
  156. return NewSamplerWithOptions(core, tick, first, thereafter)
  157. }
  158. func (s *sampler) With(fields []Field) Core {
  159. return &sampler{
  160. Core: s.Core.With(fields),
  161. tick: s.tick,
  162. counts: s.counts,
  163. first: s.first,
  164. thereafter: s.thereafter,
  165. hook: s.hook,
  166. }
  167. }
  168. func (s *sampler) Check(ent Entry, ce *CheckedEntry) *CheckedEntry {
  169. if !s.Enabled(ent.Level) {
  170. return ce
  171. }
  172. counter := s.counts.get(ent.Level, ent.Message)
  173. n := counter.IncCheckReset(ent.Time, s.tick)
  174. if n > s.first && (n-s.first)%s.thereafter != 0 {
  175. s.hook(ent, LogDropped)
  176. return ce
  177. }
  178. s.hook(ent, LogSampled)
  179. return s.Core.Check(ent, ce)
  180. }