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

Wrap existing zap loggers #13

Merged
merged 5 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
uses: golangci/[email protected]
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.56.2
version: v1.61.0

# Optional: working directory, useful for monorepos
# working-directory: somedir
Expand All @@ -45,4 +45,4 @@ jobs:
# skip-pkg-cache: true

# Optional: if set to true then the action don't cache or restore ~/.cache/go-build.
# skip-build-cache: true
# skip-build-cache: true
52 changes: 24 additions & 28 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,52 +20,48 @@ linters-settings:
linters:
enable-all: true
disable:
- copyloopvar
- depguard
- dupl # some code duplication is traded for 1 alloc
- lll
- maligned
- dupword
- errname
- exportloopref
- execinquery
- exhaustruct
- forbidigo
- forcetypeassert
- gci
- gochecknoglobals
- gomnd
- wrapcheck
- intrange
- lll
- mnd
- nonamedreturns
- paralleltest
- forbidigo
- exhaustivestruct
- interfacer # deprecated
- forcetypeassert
- scopelint # deprecated
- ifshort # too many false positives
- golint # deprecated
- varnamelen
- tagalign
- tagliatelle
- errname
- ireturn
- exhaustruct
- nonamedreturns
- nosnakecase
- structcheck
- varcheck
- deadcode
- testableexamples
- dupword
- depguard
- tagalign
- varnamelen
- wrapcheck

issues:
exclude-use-default: false
exclude-rules:
- linters:
- gomnd
- dupl
- err113
- fatcontext
- funlen
- goconst
- goerr113
- gomnd
- mnd
- noctx
- funlen
- dupl
- structcheck
- unused
- unparam
- nosnakecase
- unused
path: "_test.go"
- linters:
- errcheck # Error checking omitted for brevity.
- gosec
path: "example_"

2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#GOLANGCI_LINT_VERSION := "v1.56.2" # Optional configuration to pinpoint golangci-lint version.
GOLANGCI_LINT_VERSION := "v1.61.0"

# The head of Makefile determines location of dev-go to include standard targets.
GO ?= go
Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ logger.Error(ctx, "something failed",
logger.Important(ctx, "logged because is important")
logger.Info(ctxd.WithDebug(ctx), "logged because of forced DEBUG mode")

logger.AtomicLevel.SetLevel(zap.DebugLevel)
logger.SetLevelEnabler(zapcore.DebugLevel)
logger.Info(ctx, "logged because logger level was changed to DEBUG")

// Output:
// <stripped> ERROR zapctxd/example_test.go:23 something failed {"baz": 1, "quux": 2.2, "foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:28 logged because is important {"foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:29 logged because of forced DEBUG mode {"foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:32 logged because logger level was changed to DEBUG {"foo": "bar"}
// <stripped> ERROR zapctxd/example_test.go:26 something failed {"baz": 1, "quux": 2.2, "foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:31 logged because is important {"foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:32 logged because of forced DEBUG mode {"foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:35 logged because logger level was changed to DEBUG {"foo": "bar"}
```

## See Also
Expand Down
14 changes: 8 additions & 6 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import (
"context"

"github.com/bool64/ctxd"
"github.com/bool64/zapctxd"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"

"github.com/bool64/zapctxd"
)

func ExampleNew() {
Expand All @@ -29,12 +31,12 @@ func ExampleNew() {
logger.Important(ctx, "logged because is important")
logger.Info(ctxd.WithDebug(ctx), "logged because of forced DEBUG mode")

logger.AtomicLevel.SetLevel(zap.DebugLevel)
logger.SetLevelEnabler(zapcore.DebugLevel)
logger.Info(ctx, "logged because logger level was changed to DEBUG")

// Output:
// <stripped> ERROR zapctxd/example_test.go:24 something failed {"baz": 1, "quux": 2.2, "foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:29 logged because is important {"foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:30 logged because of forced DEBUG mode {"foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:33 logged because logger level was changed to DEBUG {"foo": "bar"}
// <stripped> ERROR zapctxd/example_test.go:26 something failed {"baz": 1, "quux": 2.2, "foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:31 logged because is important {"foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:32 logged because of forced DEBUG mode {"foo": "bar"}
// <stripped> INFO zapctxd/example_test.go:35 logged because logger level was changed to DEBUG {"foo": "bar"}
}
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ go 1.19

require (
github.com/bool64/ctxd v1.2.1
github.com/bool64/dev v0.2.34
github.com/stretchr/testify v1.8.1
github.com/bool64/dev v0.2.36
github.com/stretchr/testify v1.9.0
github.com/swaggest/assertjson v1.9.0
go.uber.org/zap v1.27.0
)
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ github.com/bool64/ctxd v1.2.1 h1:hARFteq0zdn4bwfmxLhak3fXFuvtJVKDH2X29VV/2ls=
github.com/bool64/ctxd v1.2.1/go.mod h1:ZG6QkeGVLTiUl2mxPpyHmFhDzFZCyocr9hluBV3LYuc=
github.com/bool64/dev v0.2.34 h1:P9n315P8LdpxusnYQ0X7MP1CZXwBK5ae5RZrd+GdSZE=
github.com/bool64/dev v0.2.34/go.mod h1:iJbh1y/HkunEPhgebWRNcs8wfGq7sjvJ6W5iabL8ACg=
github.com/bool64/dev v0.2.36 h1:yU3bbOTujoxhWnt8ig8t94PVmZXIkCaRj9C57OtqJBY=
github.com/bool64/dev v0.2.36/go.mod h1:iJbh1y/HkunEPhgebWRNcs8wfGq7sjvJ6W5iabL8ACg=
github.com/bool64/shared v0.1.5 h1:fp3eUhBsrSjNCQPcSdQqZxxh9bBwrYiZ+zOKFkM0/2E=
github.com/bool64/shared v0.1.5/go.mod h1:081yz68YC9jeFB3+Bbmno2RFWvGKv1lPKkMP6MHJlPs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down Expand Up @@ -35,6 +37,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/swaggest/assertjson v1.9.0 h1:dKu0BfJkIxv/xe//mkCrK5yZbs79jL7OVf9Ija7o2xQ=
github.com/swaggest/assertjson v1.9.0/go.mod h1:b+ZKX2VRiUjxfUIal0HDN85W0nHPAYUbYH5WkkSsFsU=
github.com/swaggest/usecase v1.2.0 h1:cHVFqxIbHfyTXp02JmWXk+ZADaSa87UZP+b3qL5Nz90=
Expand Down
82 changes: 57 additions & 25 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,16 @@

// Logger is a contextualized zap logger.
type Logger struct {
// Deprecated: Use SetLevelEnabler instead.
AtomicLevel zap.AtomicLevel
callerSkip bool
encoder zapcore.Encoder
sugared *zap.SugaredLogger
debug *zap.SugaredLogger
options []zap.Option
out zapcore.WriteSyncer

callerSkip bool
encoder zapcore.Encoder
levelEnabler zapcore.LevelEnabler
sugared *zap.SugaredLogger
debug *zap.SugaredLogger
options []zap.Option
out zapcore.WriteSyncer
}

// Config is log configuration.
Expand Down Expand Up @@ -64,9 +67,9 @@
}

l := Logger{
AtomicLevel: zap.NewAtomicLevelAt(level),
out: out,
options: append(cfg.ZapOptions, options...),
levelEnabler: zap.NewAtomicLevelAt(level),
out: out,
options: append(cfg.ZapOptions, options...),
}

if cfg.DevMode {
Expand Down Expand Up @@ -101,11 +104,25 @@
return &l
}

// WrapZapLoggers creates contextualized logger with provided zap loggers.
func WrapZapLoggers(sugared, debug *zap.Logger, encoder zapcore.Encoder, options ...zap.Option) *Logger {
sugared = sugared.WithOptions(options...)
debug = debug.WithOptions(options...)

return &Logger{
levelEnabler: sugared.Core(),
sugared: sugared.Sugar(),
debug: debug.Sugar(),
encoder: encoder,
options: options,
}
}

func (l *Logger) make() {
l.sugared = zap.New(zapcore.NewCore(
l.encoder,
l.out,
l.AtomicLevel,
loggerLevelEnabler(l),
), l.options...).Sugar()

l.debug = zap.New(zapcore.NewCore(
Expand All @@ -115,6 +132,15 @@
), l.options...).Sugar()
}

// SetLevelEnabler sets level enabler.
func (l *Logger) SetLevelEnabler(enabler zapcore.LevelEnabler) {
if _, ok := l.levelEnabler.(zapcore.Core); ok {
panic("cannot set level enabler when logger is created with zap loggers")
}

l.levelEnabler = enabler
}

// SkipCaller adapts logger for wrapping by increasing skip caller counter.
func (l *Logger) SkipCaller() *Logger {
if !l.callerSkip {
Expand All @@ -130,7 +156,7 @@
}

// Debug implements ctxd.Logger.
func (l *Logger) Debug(ctx context.Context, msg string, keysAndValues ...interface{}) {
func (l *Logger) Debug(ctx context.Context, msg string, keysAndValues ...any) {
z := l.get(ctx, zap.DebugLevel)
if z == nil {
return
Expand All @@ -142,7 +168,7 @@
)

if len(fv) > 0 {
kv = make([]interface{}, 0, len(fv)+len(kv))
kv = make([]any, 0, len(fv)+len(kv))

kv = append(kv, keysAndValues...)
kv = append(kv, fv...)
Expand All @@ -164,7 +190,7 @@
z.Debugw(msg, kv...)
}

func expandError(kv []interface{}, se ctxd.StructuredError, i int) []interface{} {
func expandError(kv []any, se ctxd.StructuredError, i int) []any {
kv[i] = se.Error()

tuples := se.Tuples()
Expand All @@ -189,7 +215,7 @@
}

// Info implements ctxd.Logger.
func (l *Logger) Info(ctx context.Context, msg string, keysAndValues ...interface{}) {
func (l *Logger) Info(ctx context.Context, msg string, keysAndValues ...any) {
z := l.get(ctx, zap.InfoLevel)
if z == nil {
return
Expand All @@ -201,7 +227,7 @@
)

if len(fv) > 0 {
kv = make([]interface{}, 0, len(fv)+len(kv))
kv = make([]any, 0, len(fv)+len(kv))

kv = append(kv, keysAndValues...)
kv = append(kv, fv...)
Expand All @@ -224,7 +250,7 @@
}

// Important implements ctxd.Logger.
func (l *Logger) Important(ctx context.Context, msg string, keysAndValues ...interface{}) {
func (l *Logger) Important(ctx context.Context, msg string, keysAndValues ...any) {
z := l.get(ctxd.WithDebug(ctx), zap.InfoLevel)
if z == nil {
return
Expand All @@ -236,7 +262,7 @@
)

if len(fv) > 0 {
kv = make([]interface{}, 0, len(fv)+len(kv))
kv = make([]any, 0, len(fv)+len(kv))

kv = append(kv, keysAndValues...)
kv = append(kv, fv...)
Expand All @@ -259,7 +285,7 @@
}

// Warn implements ctxd.Logger.
func (l *Logger) Warn(ctx context.Context, msg string, keysAndValues ...interface{}) {
func (l *Logger) Warn(ctx context.Context, msg string, keysAndValues ...any) {
z := l.get(ctx, zap.WarnLevel)
if z == nil {
return
Expand All @@ -271,7 +297,7 @@
)

if len(fv) > 0 {
kv = make([]interface{}, 0, len(fv)+len(kv))
kv = make([]any, 0, len(fv)+len(kv))

kv = append(kv, keysAndValues...)
kv = append(kv, fv...)
Expand All @@ -294,7 +320,7 @@
}

// Error implements ctxd.Logger.
func (l *Logger) Error(ctx context.Context, msg string, keysAndValues ...interface{}) {
func (l *Logger) Error(ctx context.Context, msg string, keysAndValues ...any) {
z := l.get(ctx, zap.ErrorLevel)
if z == nil {
return
Expand All @@ -306,7 +332,7 @@
)

if len(fv) > 0 {
kv = make([]interface{}, 0, len(fv)+len(kv))
kv = make([]any, 0, len(fv)+len(kv))

kv = append(kv, keysAndValues...)
kv = append(kv, fv...)
Expand All @@ -330,7 +356,7 @@

func (l *Logger) get(ctx context.Context, level zapcore.Level) *zap.SugaredLogger {
z := l.sugared
if !l.AtomicLevel.Enabled(level) {
if !l.levelEnabler.Enabled(level) {
z = nil
}

Expand All @@ -345,9 +371,9 @@

writer := ctxd.LogWriter(ctx)
if writer != nil {
level := zap.DebugLevel
level := zapcore.LevelEnabler(zap.DebugLevel)
if !isDebug {
level = l.AtomicLevel.Level()
level = l.levelEnabler
}

ws, ok := writer.(zapcore.WriteSyncer)
Expand All @@ -368,11 +394,17 @@
var _ ctxd.LoggerProvider = &Logger{}

// CtxdLogger provides contextualized logger.
func (l *Logger) CtxdLogger() ctxd.Logger {
func (l *Logger) CtxdLogger() ctxd.Logger { //nolint: ireturn

Check notice on line 397 in logger.go

View workflow job for this annotation

GitHub Actions / test (1.22.x)

1 statement(s) on lines 397:399 are not covered by tests.
return l
}

// ZapLogger returns *zap.Logger that used in Logger.
func (l *Logger) ZapLogger() *zap.Logger {
return l.sugared.Desugar()
}

func loggerLevelEnabler(l *Logger) zap.LevelEnablerFunc {
return func(lvl zapcore.Level) bool {
return l.levelEnabler.Enabled(lvl)
}
}
Loading
Loading