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

feat(core/zap): Make caller encoder configurable, add additional one #301

Merged
merged 7 commits into from
Feb 14, 2025
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
7 changes: 4 additions & 3 deletions core/zap/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ Use the method `.WithContext(ctx)` whenever you have a context, this will make s

## Configuration

```
```yaml
zap:
loglevel: Info
loglevel: Info # "Debug" | "Info" | "Warn" | "Error" | "DPanic" | "Panic" | "Fatal"
json: true
colored: false
devmode: false
Expand All @@ -24,7 +24,8 @@ zap:
thereafter: 100
fieldmap:
key: value

encoding:
caller: "short" # short | smart | full
```

## More about Zap
Expand Down
32 changes: 32 additions & 0 deletions core/zap/caller_encoder.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package zap

import (
"os"
"runtime"
"strings"

"go.uber.org/zap/zapcore"
)

func short(file string) string {
parts := strings.Split(file, string(os.PathSeparator))

file = ""

for i, part := range parts {
switch {
case i == len(parts)-1 || len(part) == 0:
file += part
case i == len(parts)-2:
file += part + "/"
default:
file += string(part[0]) + "/"
}
}

return file
}

func smartCallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(short(runtime.FuncForPC(caller.PC).Name()))
}
13 changes: 13 additions & 0 deletions core/zap/caller_encoder_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package zap //nolint:testpackage // explicit whitebox test

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestShort(t *testing.T) {
t.Parallel()
assert.Equal(t, "", short(""))
assert.Equal(t, "a/bbb/ccc.ddd.eee", short("aaa/bbb/ccc.ddd.eee"))
}
30 changes: 26 additions & 4 deletions core/zap/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
)

type (
// Module for logrus logging
// Module for zap logging
Module struct {
area string
json bool
Expand All @@ -24,13 +24,20 @@ type (
samplingThereafter float64
fieldMap map[string]string
logSession bool
callerEncoder zapcore.CallerEncoder
}

shutdownEventSubscriber struct {
logger flamingo.Logger
}
)

const (
ZapCallerEncoderShort = "short"
ZapCallerEncoderSmart = "smart"
ZapCallerEncoderFull = "full"
)

var logLevels = map[string]zapcore.Level{
"Trace": zap.DebugLevel - 1, // does not exist in zap by default
"Debug": zap.DebugLevel,
Expand All @@ -42,6 +49,12 @@ var logLevels = map[string]zapcore.Level{
"Fatal": zap.FatalLevel,
}

var callerEncoders = map[string]zapcore.CallerEncoder{
ZapCallerEncoderSmart: smartCallerEncoder,
ZapCallerEncoderFull: zapcore.FullCallerEncoder,
ZapCallerEncoderShort: zapcore.ShortCallerEncoder,
}

// Inject dependencies
func (m *Module) Inject(config *struct {
Area string `inject:"config:area"`
Expand All @@ -54,6 +67,7 @@ func (m *Module) Inject(config *struct {
SamplingThereafter float64 `inject:"config:core.zap.sampling.thereafter,optional"`
FieldMap config.Map `inject:"config:core.zap.fieldmap,optional"`
LogSession bool `inject:"config:core.zap.logsession,optional"`
CallerEncoder string `inject:"config:core.zap.encoding.caller,optional"`
}) {
m.area = config.Area
m.json = config.JSON
Expand All @@ -64,6 +78,11 @@ func (m *Module) Inject(config *struct {
m.samplingInitial = config.SamplingInitial
m.samplingThereafter = config.SamplingThereafter
m.logSession = config.LogSession
m.callerEncoder = callerEncoders[ZapCallerEncoderShort]

if encoder, ok := callerEncoders[config.CallerEncoder]; ok {
m.callerEncoder = encoder
}

if config.FieldMap != nil {
m.fieldMap = make(map[string]string, len(config.FieldMap))
Expand All @@ -76,7 +95,7 @@ func (m *Module) Inject(config *struct {
}
}

// Configure the zap logger as flamingo.Logger (in JSON mode kibana compatible)
// Configure the zap logger as flamingo.Logger
func (m *Module) Configure(injector *dingo.Injector) {
injector.Bind(new(flamingo.Logger)).ToInstance(m.createLoggerInstance())
flamingo.BindEventSubscriber(injector).To(shutdownEventSubscriber{})
Expand Down Expand Up @@ -128,7 +147,7 @@ func (m *Module) createLoggerInstance() *Logger {
EncodeLevel: encoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
EncodeCaller: m.callerEncoder,
EncodeName: zapcore.FullNameEncoder,
},
OutputPaths: []string{"stderr"},
Expand Down Expand Up @@ -186,8 +205,11 @@ core: zap: {
fieldmap: {
[string]: string
}
encoding: {
caller: *"%s" | "%s" | "%s"
}
}
`, allowedLevels)
`, allowedLevels, ZapCallerEncoderShort, ZapCallerEncoderSmart, ZapCallerEncoderFull)
}

// FlamingoLegacyConfigAlias mapping
Expand Down