Skip to content

Commit

Permalink
feat[accesslog]: allow log by condition
Browse files Browse the repository at this point in the history
Signed-off-by: rogerogers <[email protected]>
  • Loading branch information
rogerogers committed Nov 14, 2023
1 parent d2083b7 commit db0c379
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
33 changes: 33 additions & 0 deletions accesslog/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,36 @@ func main() {
}

```

### Log By Condition

We can add a method `logConditionFunc` to determine whether to log based on the conditions.

Sample Code:

```go
package main

import (
"context"

"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/hertz-contrib/logger/accesslog"
)

func main() {
h := server.Default(server.WithHostPorts(":8081"))
h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(200, map[string]string{"ping": "pong"})
})
h.Use(accesslog.New(accesslog.WithLogConditionFunc(func(ctx context.Context, c *app.RequestContext) bool {
if c.FullPath() == "/ping" {
return false
} else {
return true
}
})))
h.Spin()
}
```
4 changes: 4 additions & 0 deletions accesslog/accesslog.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ func new(ctx context.Context, opts ...Option) app.HandlerFunc {

c.Next(ctx)

if !cfg.logConditionFunc(ctx, c) {
return
}

if cfg.enableLatency {
stop = time.Now()
c.Set("stop", stop)
Expand Down
12 changes: 12 additions & 0 deletions accesslog/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import (
)

type (
logConditionFunc func(ctx context.Context, c *app.RequestContext) bool
// options defines the config for middleware.
options struct {
// format defines the logging tags
Expand Down Expand Up @@ -78,6 +79,7 @@ type (
// Optional. Default: time.Local
timeZoneLocation *time.Location
enableLatency bool
logConditionFunc logConditionFunc
}

Option func(o *options)
Expand All @@ -93,6 +95,9 @@ func newOptions(opts ...Option) *options {
timeZoneLocation: time.Local,
timeInterval: 500 * time.Millisecond,
logFunc: hlog.CtxInfof,
logConditionFunc: func(ctx context.Context, c *app.RequestContext) bool {
return true
},
}

for _, opt := range opts {
Expand Down Expand Up @@ -136,3 +141,10 @@ func WithTimeZoneLocation(loc *time.Location) Option {
o.timeZoneLocation = loc
}
}

// WithLogConditionFunc set logConditionFunc
func WithLogConditionFunc(f logConditionFunc) Option {
return func(o *options) {
o.logConditionFunc = f
}
}

0 comments on commit db0c379

Please sign in to comment.