Skip to content

Commit

Permalink
feat: support silentmode to mute log
Browse files Browse the repository at this point in the history
  • Loading branch information
Duslia committed Apr 24, 2023
1 parent 4a6d3b1 commit e4eb2c2
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
23 changes: 23 additions & 0 deletions pkg/app/server/hertz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"github.com/cloudwego/hertz/pkg/app/server/registry"
"github.com/cloudwego/hertz/pkg/common/config"
errs "github.com/cloudwego/hertz/pkg/common/errors"
"github.com/cloudwego/hertz/pkg/common/hlog"
"github.com/cloudwego/hertz/pkg/common/test/assert"
"github.com/cloudwego/hertz/pkg/common/test/mock"
"github.com/cloudwego/hertz/pkg/common/utils"
Expand Down Expand Up @@ -740,3 +741,25 @@ func TestOnprepare(t *testing.T) {
time.Sleep(time.Second)
c.Get(context.Background(), nil, "http://127.0.0.1:9231/ping")
}

func TestSilentMode(t *testing.T) {
hlog.SetSilentMode(true)
b := bytes.NewBuffer(nil)
hlog.SetOutput(b)

h := New(WithHostPorts("localhost:9232"), WithTransport(standard.NewTransporter))
h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.Write([]byte("hello, world"))
})
go h.Spin()
time.Sleep(time.Second)

d := standard.NewDialer()
conn, _ := d.DialConnection("tcp", "127.0.0.1:9232", 0, nil)
conn.Write([]byte("aaa"))
conn.Close()

if strings.Contains(b.String(), "Error") {
t.Fatalf("unexpected error in log: %s", b.String())
}
}
11 changes: 11 additions & 0 deletions pkg/common/hlog/system.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ import (
"sync"
)

var silentMode = false

func SetSilentMode(s bool) {
silentMode = s
}

const MuteError = "Error=%s, remoteAddr=%s"

var builderPool = sync.Pool{New: func() interface{} {
return &strings.Builder{} // nolint:SA6002
}}
Expand Down Expand Up @@ -80,6 +88,9 @@ func (ll *systemLogger) Fatalf(format string, v ...interface{}) {
}

func (ll *systemLogger) Errorf(format string, v ...interface{}) {
if silentMode && format == MuteError {
return
}
ll.logger.Errorf(ll.addPrefix(format), v...)
}

Expand Down

0 comments on commit e4eb2c2

Please sign in to comment.