Skip to content

Commit

Permalink
Fix log depth for DelegatingLogSink
Browse files Browse the repository at this point in the history
  • Loading branch information
alculquicondor committed Aug 10, 2022
1 parent bcde6f0 commit ca3b341
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
9 changes: 6 additions & 3 deletions examples/scratch-env/main.go
Expand Up @@ -21,10 +21,11 @@ import (
"os"

flag "github.com/spf13/pflag"
"go.uber.org/zap"

ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/envtest"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
logzap "sigs.k8s.io/controller-runtime/pkg/log/zap"
)

var (
Expand All @@ -35,16 +36,18 @@ var (

// have a separate function so we can return an exit code w/o skipping defers
func runMain() int {
loggerOpts := &zap.Options{
loggerOpts := &logzap.Options{
Development: true, // a sane default
ZapOpts: []zap.Option{zap.AddCaller()},
}
{
var goFlagSet goflag.FlagSet
loggerOpts.BindFlags(&goFlagSet)
flag.CommandLine.AddGoFlagSet(&goFlagSet)
}
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseFlagOptions(loggerOpts)))
ctrl.SetLogger(logzap.New(logzap.UseFlagOptions(loggerOpts)))
ctrl.Log.Info("Starting...")

log := ctrl.Log.WithName("main")

Expand Down
15 changes: 13 additions & 2 deletions pkg/log/deleg.go
Expand Up @@ -73,6 +73,9 @@ func (p *loggerPromise) Fulfill(parentLogSink logr.LogSink) {

p.logger.lock.Lock()
p.logger.logger = sink
if withCallDepth, ok := sink.(logr.CallDepthLogSink); ok {
p.logger.logger = withCallDepth.WithCallDepth(1)
}
p.logger.promise = nil
p.logger.lock.Unlock()

Expand Down Expand Up @@ -141,7 +144,11 @@ func (l *DelegatingLogSink) WithName(name string) logr.LogSink {
defer l.lock.RUnlock()

if l.promise == nil {
return l.logger.WithName(name)
sink := l.logger.WithName(name)
if withCallDepth, ok := sink.(logr.CallDepthLogSink); ok {
sink = withCallDepth.WithCallDepth(-1)
}
return sink
}

res := &DelegatingLogSink{logger: l.logger}
Expand All @@ -157,7 +164,11 @@ func (l *DelegatingLogSink) WithValues(tags ...interface{}) logr.LogSink {
defer l.lock.RUnlock()

if l.promise == nil {
return l.logger.WithValues(tags...)
sink := l.logger.WithValues(tags...)
if withCallDepth, ok := sink.(logr.CallDepthLogSink); ok {
sink = withCallDepth.WithCallDepth(-1)
}
return sink
}

res := &DelegatingLogSink{logger: l.logger}
Expand Down
2 changes: 1 addition & 1 deletion pkg/log/zap/zap.go
Expand Up @@ -244,7 +244,7 @@ func NewRaw(opts ...Opts) *zap.Logger {
// this basically mimics New<type>Config, but with a custom sink
sink := zapcore.AddSync(o.DestWriter)

o.ZapOpts = append(o.ZapOpts, zap.AddCallerSkip(1), zap.ErrorOutput(sink))
o.ZapOpts = append(o.ZapOpts, zap.ErrorOutput(sink))
log := zap.New(zapcore.NewCore(&KubeAwareEncoder{Encoder: o.Encoder, Verbose: o.Development}, sink, o.Level))
log = log.WithOptions(o.ZapOpts...)
return log
Expand Down

0 comments on commit ca3b341

Please sign in to comment.