From 22991dc46df8f9833b311477474e8dd7ce562cb4 Mon Sep 17 00:00:00 2001 From: Mitja T Date: Wed, 31 Jan 2024 21:28:00 -0800 Subject: [PATCH] logging: Pogreb now logs into our logger, not stderr --- cmd/common/common.go | 6 ++++++ log/log.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/cmd/common/common.go b/cmd/common/common.go index c6572336c..a5cbd9e99 100644 --- a/cmd/common/common.go +++ b/cmd/common/common.go @@ -4,8 +4,10 @@ package common import ( "fmt" "io" + stdLog "log" "os" + "github.com/akrylysov/pogreb" coreLogging "github.com/oasisprotocol/oasis-core/go/common/logging" "github.com/oasisprotocol/nexus/config" @@ -50,6 +52,10 @@ func Init(cfg *config.Config) error { return err } + // Initialize pogreb logging. + pogrebLogger := RootLogger().WithModule("pogreb").WithCallerUnwind(7) + pogreb.SetLogger(stdLog.New(log.WriterIntoLogger(*pogrebLogger), "", 0)) + // Initialize Prometheus service. if cfg.Metrics != nil { promServer, err := metrics.NewPullService(cfg.Metrics.PullEndpoint, rootLogger) diff --git a/log/log.go b/log/log.go index 6a1939b48..d0fbbeb54 100644 --- a/log/log.go +++ b/log/log.go @@ -112,7 +112,40 @@ func (l *Logger) WithModule(module string) *Logger { } } +// WithCallerUnwind returns a clone of the logger where the `caller` +// value will show the n-th entry on the call stack at the time of logging. +func (l *Logger) WithCallerUnwind(n int) *Logger { + return &Logger{ + logger: log.With(l.logger, "caller", log.Caller(n)), + level: l.level, + module: l.module, + } +} + // Level is the logging level. func (l *Logger) Level() Level { return l.level } + +// An io.Writer impl that writes every string to the backing logger `l` at Info level. +type writerIntoLoggerImpl struct { + Logger +} + +var _ io.Writer = (*writerIntoLoggerImpl)(nil) + +func (l *writerIntoLoggerImpl) Write(msg []byte) (n int, err error) { + // Strip trailing newlines from message. + origLen := len(msg) + for len(msg) > 0 && msg[len(msg)-1] == '\n' { + msg = msg[:len(msg)-1] + } + + // Write message to backing logger. + l.Info(string(msg)) + return origLen, nil +} + +func WriterIntoLogger(l Logger) io.Writer { + return &writerIntoLoggerImpl{l} +}