Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core/sampler: Support decision hook #813

Merged
merged 17 commits into from Apr 21, 2020
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion benchmarks/zap_test.go
Expand Up @@ -116,7 +116,7 @@ func newZapLogger(lvl zapcore.Level) *zap.Logger {
}

func newSampledLogger(lvl zapcore.Level) *zap.Logger {
return zap.New(zapcore.NewSampler(
return zap.New(zapcore.NewSamplerWithOptions(
newZapLogger(zap.DebugLevel).Core(),
100*time.Millisecond,
10, // first
Expand Down
21 changes: 18 additions & 3 deletions config.go
Expand Up @@ -32,10 +32,15 @@ import (
// global CPU and I/O load that logging puts on your process while attempting
// to preserve a representative subset of your logs.
//
// Values configured here are per-second. See zapcore.NewSampler for details.
// Hook is called whenever a Sampler makes a decision. Currently, whenever a
// log is dropped.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second part no longer true. How about,

Suggested change
// Hook is called whenever a Sampler makes a decision. Currently, whenever a
// log is dropped.
// If specified, the Sampler will invoke the Hook after each decision.

//
// Values configured here are per-second. See zapcore.NewSamplerWithOptions for
// details.
type SamplingConfig struct {
Initial int `json:"initial" yaml:"initial"`
Thereafter int `json:"thereafter" yaml:"thereafter"`
Hook func(zapcore.Entry, zapcore.SamplingDecision)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should add json:"-" yaml:"-" so the JSON/YAML moduels do not attempt to serialize this.

Suggested change
Hook func(zapcore.Entry, zapcore.SamplingDecision)
Hook func(zapcore.Entry, zapcore.SamplingDecision) `json:"-" yaml:"-"`

}

// Config offers a declarative way to construct a logger. It doesn't do
Expand Down Expand Up @@ -208,9 +213,19 @@ func (cfg Config) buildOptions(errSink zapcore.WriteSyncer) []Option {
opts = append(opts, AddStacktrace(stackLevel))
}

if cfg.Sampling != nil {
if scfg := cfg.Sampling; scfg != nil {
opts = append(opts, WrapCore(func(core zapcore.Core) zapcore.Core {
return zapcore.NewSampler(core, time.Second, int(cfg.Sampling.Initial), int(cfg.Sampling.Thereafter))
var samplerOpts []zapcore.SamplerOption
if scfg.Hook != nil {
samplerOpts = append(samplerOpts, zapcore.SamplerHook(scfg.Hook))
}
return zapcore.NewSamplerWithOptions(
core,
time.Second,
cfg.Sampling.Initial,
cfg.Sampling.Thereafter,
samplerOpts...,
)
}))
}

Expand Down
70 changes: 70 additions & 0 deletions config_test.go
Expand Up @@ -27,6 +27,7 @@ import (

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/atomic"
"go.uber.org/zap/zapcore"
)

Expand Down Expand Up @@ -144,3 +145,72 @@ func TestConfigWithMissingAttributes(t *testing.T) {
})
}
}

func makeSamplerCountingHook() (func(zapcore.Entry, zapcore.SamplingDecision),
*atomic.Int64, *atomic.Int64) {
shirchen marked this conversation as resolved.
Show resolved Hide resolved
droppedCount := &atomic.Int64{}
sampledCount := &atomic.Int64{}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: use new for pointers to zero value.

Suggested change
droppedCount := &atomic.Int64{}
sampledCount := &atomic.Int64{}
droppedCount := new(atomic.Int64)
sampledCount := new(atomic.Int64)

The other convention is var and & before returning:

Suggested change
droppedCount := &atomic.Int64{}
sampledCount := &atomic.Int64{}
var dropped, sampled atomic.Int64
  return h, &dropped, &sampled

h := func(_ zapcore.Entry, dec zapcore.SamplingDecision) {
if dec == zapcore.LogDropped {
droppedCount.Inc()
} else if dec == zapcore.LogSampled {
sampledCount.Inc()
}
}
return h, droppedCount, sampledCount
}

func TestConfigWithSamplingHook(t *testing.T) {
shook, dcount, scount := makeSamplerCountingHook()
cfg := Config{
Level: NewAtomicLevelAt(InfoLevel),
Development: false,
Sampling: &SamplingConfig{
Initial: 100,
Thereafter: 100,
Hook: shook,
},
Encoding: "json",
EncoderConfig: NewProductionEncoderConfig(),
OutputPaths: []string{"stderr"},
ErrorOutputPaths: []string{"stderr"},
}
expectN := 2 + 100 + 1 // 2 from initial logs, 100 initial sampled logs, 1 from off-by-one in sampler
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we fix the off-by-one, seems a little odd, haven't looked into where it's coming from

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea, I didn't verify the comment and copied from another test. Fixed explanation.

expectRe := `{"level":"info","caller":"zap/config_test.go:\d+","msg":"info","k":"v","z":"zz"}` + "\n" +
`{"level":"warn","caller":"zap/config_test.go:\d+","msg":"warn","k":"v","z":"zz"}` + "\n"
expectDropped := 99 // 200 - 100 initial - 1 thereafter
expectSampled := 103 // 2 from initial + 100 + 1 thereafter
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is this the same as expectN? we expect the hook to be called on every log, and then expectDropped + expectSampled == expectN?

Copy link
Contributor Author

@shirchen shirchen Apr 15, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

expectN is not a count from samplerHook, but from a zap hook which only measures what is sent. i regret carrying over a hook from another test now as it seems to cause confusion. :)


temp, err := ioutil.TempFile("", "zap-prod-config-test")
require.NoError(t, err, "Failed to create temp file.")
defer func() {
err := os.Remove(temp.Name())
if err != nil {
return
}
}()

cfg.OutputPaths = []string{temp.Name()}
cfg.EncoderConfig.TimeKey = "" // no timestamps in tests
cfg.InitialFields = map[string]interface{}{"z": "zz", "k": "v"}

hook, count := makeCountingHook()
logger, err := cfg.Build(Hooks(hook))
require.NoError(t, err, "Unexpected error constructing logger.")

logger.Debug("debug")
logger.Info("info")
logger.Warn("warn")

byteContents, err := ioutil.ReadAll(temp)
require.NoError(t, err, "Couldn't read log contents from temp file.")
logs := string(byteContents)
assert.Regexp(t, expectRe, logs, "Unexpected log output.")

for i := 0; i < 200; i++ {
logger.Info("sampling")
}
assert.Equal(t, int64(expectN), count.Load(), "Hook called an unexpected number of times.")
assert.Equal(t, int64(expectDropped), dcount.Load())
assert.Equal(t, int64(expectSampled), scount.Load())
}
82 changes: 79 additions & 3 deletions zapcore/sampler.go
Expand Up @@ -81,17 +81,87 @@ func (c *counter) IncCheckReset(t time.Time, tick time.Duration) uint64 {
return 1
}

// SamplingDecision represents a decision made by sampler.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: all types represent something. can do:

Suggested change
// SamplingDecision represents a decision made by sampler.
// SamplingDecision is a decision made by sampler.

type SamplingDecision uint8
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm guessing this is so that it takes one byte instead of 8?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup, as byte is an alias to uint8.


const (
// LogDropped means that a log was dropped.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// LogDropped means that a log was dropped.
// LogDropped indicates that the Sampler dropped a log entry.

LogDropped SamplingDecision = iota
// LogSampled means that a log was successfully sampled.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// LogSampled means that a log was successfully sampled.
// LogSampled indicates that the Sampler sampled a log entry.

LogSampled
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

something to discuss

  • it would be useful to know when a log was first dropped, and then first log after the sample again. e.g., if you want to add a special log that said "message X is now being dropped, no further logs"?
  • doing this in the hook requires doing the same thing the sampler does, probably more inefficiently (a map by message)

Copy link
Collaborator

@abhinav abhinav Apr 13, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just an idea: If we make SamplingDecision a bitfield, we could do that separately and re-use sampler logic

LogDropped SamplingDecision = 1 << iota
LogDroppedInitial
LogSampled
LogSampledThereafter

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good idea, I like the idea of a bit field, so users can just check decision & LogSampled > 0 to see if it was sampled.

we might want to make that clear in the comments that users should check this like a bit field (or maybe we provide a helper on the type to do that).

We could expand this to have:

  • log sampled because it's within the initial
  • log sampled because it's the thereafter
  • log dropped (first log after initial sampled logs)
  • log dropped (first log after thereafter sampled log)
  • log dropped (other)

)

// optionFunc wraps a func so it satisfies the SamplerOption interface.
type optionFunc func(*sampler)

func (f optionFunc) apply(s *sampler) {
f(s)
}

// SamplerOption configures a Sampler option.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// SamplerOption configures a Sampler option.
// SamplerOption configures a Sampler.

type SamplerOption interface {
apply(*sampler)
}

// NopSamplingHook is the default hook used by sampler.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we actually need to export this? We'll use this if unset.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe if someone wants to test this as NewSampler* constructors are public?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NewSampler can be public but I mean the implementation of a no-op hook. Users don't really need access to that; they can write their own empty function, or just not provide the SamplingHook option.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree, not even sure if we need this in the production code, we could keep it in the test file?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's production. The sampler defaults the hook field to NopSamplingHook.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see, in that case, can we unexport and keep it here?

func NopSamplingHook(_ Entry, _ SamplingDecision) {}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can drop _ when they're all _

Suggested change
func NopSamplingHook(_ Entry, _ SamplingDecision) {}
func NopSamplingHook(Entry, SamplingDecision) {}


// SamplerHook registers a function which will be called when Sampler makes a
// decision. Currently a hook is called when a log is dropped and
// zapcore.LogDropped decision is emitted.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second part no longer true.

Suggested change
// decision. Currently a hook is called when a log is dropped and
// zapcore.LogDropped decision is emitted.
// decision.

//
// This hook is useful for side effects, for example emitting number of dropped
// logs. Note, there is no access to Fields in this hook. In the future, this
// hook can be expanded to emit whether this is first entry that was dropped,
// first after a period, etc.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would avoid mentioning future plans in documentation. That's a comment-level thing, possibly referencing tickets.

Suggested change
// This hook is useful for side effects, for example emitting number of dropped
// logs. Note, there is no access to Fields in this hook. In the future, this
// hook can be expanded to emit whether this is first entry that was dropped,
// first after a period, etc.
// This hook may be used to get visibility into the performance of the sampler.
// For example, use it to track metrics of dropped versus sampled logs.

func SamplerHook(hook func(entry Entry, dec SamplingDecision)) SamplerOption {
return optionFunc(func(s *sampler) {
s.hook = hook
})
}

// NewSamplerWithOptions creates a Core that samples incoming entries, which
// caps the CPU and I/O load of logging while attempting to preserve a
// representative subset of your logs.
//
// Zap samples by logging the first N entries with a given level and message
// each tick. If more Entries with the same level and message are seen during
// the same interval, every Mth message is logged and the rest are dropped.
//
// Sampler also accepts an optional hook that can be used to count number of
// dropped logs.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Sampler also accepts an optional hook that can be used to count number of
// dropped logs.
// Sampler can be configured to report sampling decisions with the SamplerHook
// option.

//
// Keep in mind that zap's sampling implementation is optimized for speed over
// absolute precision; under load, each tick may be slightly over- or
// under-sampled.
func NewSamplerWithOptions(core Core, tick time.Duration, first, thereafter int, opts ...SamplerOption) Core {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we want to reduce the added API surface (E.g., new function that looks similar + new types), we could add a Build method on the SamplingConfig struct, similar to the Build method on the Configuration struct:
https://pkg.go.dev/go.uber.org/zap?tab=doc#Config.Build

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't we still want a means of building the sampler directly?
Config.Build is porcelain for zap.New. Anything you can do with Config.Build,
you can do with zap.New.
IMO SamplingConfig would need to match that: the underlying constructor would
need to provide the same functionality—unless we decide to deprecate direct
constructors and switch to Config structs.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

true, I'm not sure how valuable the direct structs have been vs configs, but don't have to make that change here. let's keep this as-is

s := &sampler{
Core: core,
tick: tick,
counts: newCounters(),
first: uint64(first),
thereafter: uint64(thereafter),
hook: NopSamplingHook,
}
for _, opt := range opts {
opt.apply(s)
}

return s
}

type sampler struct {
Core

counts *counters
tick time.Duration
first, thereafter uint64
hook func(Entry, SamplingDecision)
}

// NewSampler creates a Core that samples incoming entries, which caps the CPU
// and I/O load of logging while attempting to preserve a representative subset
// of your logs.
// NewSampler creates a Core that samples incoming entries, which
// caps the CPU and I/O load of logging while attempting to preserve a
// representative subset of your logs.
//
// Zap samples by logging the first N entries with a given level and message
// each tick. If more Entries with the same level and message are seen during
Expand All @@ -100,13 +170,16 @@ type sampler struct {
// Keep in mind that zap's sampling implementation is optimized for speed over
// absolute precision; under load, each tick may be slightly over- or
// under-sampled.
//
// Deprecated: use NewSamplerWithOptions.
shirchen marked this conversation as resolved.
Show resolved Hide resolved
func NewSampler(core Core, tick time.Duration, first, thereafter int) Core {
return &sampler{
Core: core,
tick: tick,
counts: newCounters(),
first: uint64(first),
thereafter: uint64(thereafter),
hook: NopSamplingHook,
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should make it so that the old implementation calls the new one so that if we make changes to sample initialization, they don't have to go in two places.

Suggested change
return &sampler{
Core: core,
tick: tick,
counts: newCounters(),
first: uint64(first),
thereafter: uint64(thereafter),
hook: NopSamplingHook,
}
return NewSamplerWithOptions(core, tick, first, thereafter)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call.

}

Expand All @@ -117,6 +190,7 @@ func (s *sampler) With(fields []Field) Core {
counts: s.counts,
first: s.first,
thereafter: s.thereafter,
hook: s.hook,
}
}

Expand All @@ -128,7 +202,9 @@ func (s *sampler) Check(ent Entry, ce *CheckedEntry) *CheckedEntry {
counter := s.counts.get(ent.Level, ent.Message)
n := counter.IncCheckReset(ent.Time, s.tick)
if n > s.first && (n-s.first)%s.thereafter != 0 {
s.hook(ent, LogDropped)
return ce
}
s.hook(ent, LogSampled)
return s.Core.Check(ent, ce)
}
50 changes: 49 additions & 1 deletion zapcore/sampler_bench_test.go
Expand Up @@ -25,6 +25,7 @@ import (
"testing"
"time"

"go.uber.org/atomic"
"go.uber.org/zap/internal/ztest"
. "go.uber.org/zap/zapcore"
)
Expand Down Expand Up @@ -203,7 +204,7 @@ var counterTestCases = [][]string{
func BenchmarkSampler_Check(b *testing.B) {
for _, keys := range counterTestCases {
b.Run(fmt.Sprintf("%v keys", len(keys)), func(b *testing.B) {
fac := NewSampler(
fac := NewSamplerWithOptions(
NewCore(
NewJSONEncoder(testEncoderConfig()),
&ztest.Discarder{},
Expand All @@ -228,3 +229,50 @@ func BenchmarkSampler_Check(b *testing.B) {
})
}
}

func makeSamplerCountingHook() (func(_ Entry, dec SamplingDecision), *atomic.Int64, *atomic.Int64) {
droppedCount := &atomic.Int64{}
sampledCount := &atomic.Int64{}
h := func(_ Entry, dec SamplingDecision) {
if dec == LogDropped {
droppedCount.Inc()
} else if dec == LogSampled {
sampledCount.Inc()
}
}
return h, droppedCount, sampledCount
}

func BenchmarkSampler_CheckWithHook(b *testing.B) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

optional: count dropped messages only to more accurately measure the use case we're trying to satisfy here.

hook, _, _ := makeSamplerCountingHook()
for _, keys := range counterTestCases {
b.Run(fmt.Sprintf("%v keys", len(keys)), func(b *testing.B) {
fac := NewSamplerWithOptions(
NewCore(
NewJSONEncoder(testEncoderConfig()),
&ztest.Discarder{},
DebugLevel,
),
time.Millisecond,
1,
1000,
SamplerHook(hook),
)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
ent := Entry{
Level: DebugLevel + Level(i%4),
Message: keys[i],
}
_ = fac.Check(ent, nil)
i++
if n := len(keys); i >= n {
i -= n
}
}
})
})
}
}
3 changes: 2 additions & 1 deletion zapcore/sampler_test.go
Expand Up @@ -37,6 +37,7 @@ import (

func fakeSampler(lvl LevelEnabler, tick time.Duration, first, thereafter int) (Core, *observer.ObservedLogs) {
core, logs := observer.New(lvl)
// Keep using deprecated constructor for cc.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is cc and why can't this be updated?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

code coverage

core = NewSampler(core, tick, first, thereafter)
return core, logs
}
Expand Down Expand Up @@ -162,7 +163,7 @@ func TestSamplerConcurrent(t *testing.T) {

tick := ztest.Timeout(10 * time.Millisecond)
cc := &countingCore{}
sampler := NewSampler(cc, tick, logsPerTick, 100000)
sampler := NewSamplerWithOptions(cc, tick, logsPerTick, 100000)

var (
done atomic.Bool
Expand Down