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[accesslog]: allow log by condition #45

Merged
merged 1 commit into from
Nov 14, 2023
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
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
}
}
Loading