diff --git a/zap.go b/zap.go index 3ed42b5..28451dc 100644 --- a/zap.go +++ b/zap.go @@ -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. @@ -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() { diff --git a/zap_test.go b/zap_test.go index 425dcc4..46b702f 100644 --- a/zap_test.go +++ b/zap_test.go @@ -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 @@ -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) } @@ -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) { @@ -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) }