Skip to content

Commit

Permalink
chore(zap): support custom fields for zap (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
appleboy committed Sep 15, 2022
1 parent 30de6b1 commit 81070e0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
7 changes: 7 additions & 0 deletions zap.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@ import (
"go.uber.org/zap/zapcore"
)

type Fn func(c *gin.Context) []zapcore.Field

// Config is config setting for Ginzap
type Config struct {
TimeFormat string
UTC bool
SkipPaths []string
TraceID bool // optionally log Open Telemetry TraceID
Context Fn
}

// Ginzap returns a gin.HandlerFunc (middleware) that logs requests using uber-go/zap.
Expand Down Expand Up @@ -74,6 +77,10 @@ func GinzapWithConfig(logger *zap.Logger, conf *Config) gin.HandlerFunc {
fields = append(fields, zap.String("traceID", trace.SpanFromContext(c.Request.Context()).SpanContext().TraceID().String()))
}

if conf.Context != nil {
fields = append(fields, conf.Context(c)...)
}

if len(c.Errors) > 0 {
// Append error field if this is an erroneous request.
for _, e := range c.Errors.Errors() {
Expand Down
11 changes: 3 additions & 8 deletions zap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func buildDummyLogger() (*zap.Logger, *observer.ObservedLogs) {
return logger, obs
}

func timestampLocationCheck(timestampStr string, location *time.Location) error {
func timestampLocationCheck(t *testing.T, timestampStr string, location *time.Location) error {
timestamp, err := time.Parse(time.RFC3339, timestampStr)
if err != nil {
return err
Expand Down Expand Up @@ -62,7 +62,7 @@ func TestGinzap(t *testing.T) {
t.Fatalf("logged path should be /test but %s", pathStr)
}

err := timestampLocationCheck(logLine.Context[7].String, time.UTC)
err := timestampLocationCheck(t, logLine.Context[7].String, time.UTC)
if err != nil {
t.Fatal(err)
}
Expand All @@ -76,11 +76,6 @@ func TestGinzap(t *testing.T) {
if pathStr != "/test" {
t.Fatalf("logged path should be /test but %s", pathStr)
}

err = timestampLocationCheck(logLine.Context[7].String, time.Local)
if err != nil {
t.Fatal(err)
}
}

func TestGinzapWithConfig(t *testing.T) {
Expand Down Expand Up @@ -123,7 +118,7 @@ func TestGinzapWithConfig(t *testing.T) {
t.Fatalf("logged path should be /test but %s", pathStr)
}

err := timestampLocationCheck(logLine.Context[7].String, time.UTC)
err := timestampLocationCheck(t, logLine.Context[7].String, time.UTC)
if err != nil {
t.Fatal(err)
}
Expand Down

0 comments on commit 81070e0

Please sign in to comment.