Skip to content

Instantly share code, notes, and snippets.

@jstangroome
Last active April 5, 2023 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstangroome/0ffb60d175ec17651a1ba71395e352b4 to your computer and use it in GitHub Desktop.
Save jstangroome/0ffb60d175ec17651a1ba71395e352b4 to your computer and use it in GitHub Desktop.
Adapter to enable gradual migration from hashicorp/logutils to uber/zap
import (
"io"
"regexp"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Replaces hashicorp/logutils by directing Golang's log package to Zap but
// extracting the log level from any `[$severity]` pattern in the message.
// Intended to enable gradual migration to structured logging.
type ZapAdapter struct {
logger *zap.Logger
defaultLevel zapcore.Level
pattern *regexp.Regexp
}
// Example: log.SetOutput(NewZapAdapter(zlog, zapcore.DebugLevel))
func NewZapAdapter(logger *zap.Logger, defaultLevel zapcore.Level) io.Writer {
return &ZapAdapter{
logger: logger,
defaultLevel: defaultLevel,
pattern: regexp.MustCompile(`\[(DEBUG|ERROR|INFO|WARN)\]`),
}
}
func (a *ZapAdapter) Write(b []byte) (int, error) {
lvl := a.defaultLevel
submatches := a.pattern.FindSubmatch(b)
if len(submatches) == 2 {
plvl, err := zapcore.ParseLevel(string(submatches[1]))
if err == nil {
lvl = plvl
}
}
a.logger.Log(lvl, string(b))
return len(b), nil
}
@pavelnikolov
Copy link

Maybe use ^ to only look at the beginning of the string or do some prefix search:

regexp.MustCompile(`^\[(DEBUG|ERROR|INFO|WARN)\]`)

@jstangroome
Copy link
Author

jstangroome commented Mar 22, 2023

@pavelnikolov I had started with a prefix-only search then realised that hashicorp/logutils matches a severity pattern anywhere in the line, so I honoured that logic.
https://github.com/hashicorp/logutils/blob/127077f645bf3162cff69c6518f7da4f0b0409e2/level.go#L38-L46

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment