Repository: cloudwego/hertz
Pull request #745 (2023-04-24 04:48:47)

feat: support silentmode to mute engine log
#### What type of PR is this?
<!--
Add one of the following kinds:

build: Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)
ci: Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)
docs: Documentation only changes
feat: A new feature
optimize: A new optimization
fix: A bug fix
perf: A code change that improves performance
refactor: A code change that neither fixes a bug nor adds a feature
style: Changes that do not affect the meaning of the code (white space, formatting, missing semi-colons, etc)
test: Adding missing tests or correcting existing tests
chore: Changes to the build process or auxiliary tools and libraries such as documentation generation
-->
feat
#### Check the PR title.
<!--
The description of the title will be attached in Release Notes, 
so please describe it from user-oriented, what this PR does / why we need it.
Please check your PR title with the below requirements:
-->
- [x] This PR title match the format: `<type>(optional scope): <description>`.
- [x] The description of this PR title is user-oriented and clear enough for others to understand.
- [x] Attach the PR updating the user documentation if the current PR requires user awareness at the usage level. [User docs repo](https://github.com/cloudwego/cloudwego.github.io).

#### (Optional) Translate the PR title into Chinese.
支持`安静模式`关闭 engine 的 log

#### (Optional) More detail description for this PR(en: English/zh: Chinese).
<!--
Provide more detailed info for review. If it is a perf type PR, perf data is suggested to give.
-->
en: support silentmode to mute engine log
zh(optional): 支持`安静模式`关闭 engine 的 log

#### (Optional) Which issue(s) this PR fixes:
<!--
Automatically closes linked issue when PR is merged.
Eg: `Fixes #<issue number>`, or `Fixes (paste link of issue)`.
-->

#### (Optional) The PR that updates user documentation:
<!--
If the current PR requires user awareness at the usage level, please submit a PR to update user docs. [User docs repo](https://github.com/cloudwego/cloudwego.github.io)
-->
https://github.com/cloudwego/cloudwego.github.io/pull/632


codecov[bot]: ## [Codecov](https://codecov.io/gh/cloudwego/hertz/pull/745?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego) Report
Patch coverage has no change and project coverage change: **`-0.04`** :warning:
> Comparison is base [(`4a6d3b1`)](https://codecov.io/gh/cloudwego/hertz/commit/4a6d3b12720f0d96785b347df7f3f1a0f0134fcf?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego) 75.72% compared to head [(`bf06bdc`)](https://codecov.io/gh/cloudwego/hertz/pull/745?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego) 75.69%.

> :exclamation: Current head bf06bdc differs from pull request most recent head cb4b481. Consider uploading reports for the commit cb4b481 to get more accurate results

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff             @@
##           develop     #745      +/-   ##
===========================================
- Coverage    75.72%   75.69%   -0.04%     
===========================================
  Files           97       97              
  Lines         9464     9468       +4     
===========================================
  Hits          7167     7167              
- Misses        1849     1852       +3     
- Partials       448      449       +1     
```


| [Impacted Files](https://codecov.io/gh/cloudwego/hertz/pull/745?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego) | Coverage Δ | |
|---|---|---|
| [pkg/common/hlog/system.go](https://codecov.io/gh/cloudwego/hertz/pull/745?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego#diff-cGtnL2NvbW1vbi9obG9nL3N5c3RlbS5nbw==) | `80.88% <0.00%> (-5.06%)` | :arrow_down: |

Help us with your feedback. Take ten seconds to tell us [how you rate us](https://about.codecov.io/nps?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego). Have a feature suggestion? [Share it here.](https://app.codecov.io/gh/feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego)

</details>

[:umbrella: View full report in Codecov by Sentry](https://codecov.io/gh/cloudwego/hertz/pull/745?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego).   
:loudspeaker: Do you have feedback about the report comment? [Let us know in this issue](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=cloudwego).


Patch:
diff --git a/pkg/common/hlog/consts.go b/pkg/common/hlog/consts.go
new file mode 100644
index 0000000..e0d31bb
--- /dev/null
+++ b/pkg/common/hlog/consts.go
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2023 CloudWeGo Authors
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package hlog
+
+const (
+	systemLogPrefix = "HERTZ: "
+
+	EngineErrorFormat = "Error=%s, remoteAddr=%s"
+)
diff --git a/pkg/common/hlog/hlog.go b/pkg/common/hlog/hlog.go
index 11a8161..7f73aaa 100644
--- a/pkg/common/hlog/hlog.go
+++ b/pkg/common/hlog/hlog.go
@@ -22,10 +22,6 @@ import (
 	"os"
 )
 
-const (
-	systemLogPrefix = "HERTZ: "
-)
-
 var (
 	// Provide default logger for users to use
 	logger FullLogger = &defaultLogger{
diff --git a/pkg/common/hlog/system.go b/pkg/common/hlog/system.go
index cb8a145..6d2b86b 100644
--- a/pkg/common/hlog/system.go
+++ b/pkg/common/hlog/system.go
@@ -23,6 +23,15 @@ import (
 	"sync"
 )
 
+var silentMode = false
+
+// SetSilentMode is used to mute engine error log,
+// for example: error when reading request headers.
+// If true, hertz engine will mute it.
+func SetSilentMode(s bool) {
+	silentMode = s
+}
+
 var builderPool = sync.Pool{New: func() interface{} {
 	return &strings.Builder{} // nolint:SA6002
 }}
@@ -80,6 +89,9 @@ func (ll *systemLogger) Fatalf(format string, v ...interface{}) {
 }
 
 func (ll *systemLogger) Errorf(format string, v ...interface{}) {
+	if silentMode && format == EngineErrorFormat {
+		return
+	}
 	ll.logger.Errorf(ll.addPrefix(format), v...)
 }
 
diff --git a/pkg/route/engine.go b/pkg/route/engine.go
index 8a9a00b..10cffac 100644
--- a/pkg/route/engine.go
+++ b/pkg/route/engine.go
@@ -459,7 +459,7 @@ func errProcess(conn io.Closer, err error) {
 		}
 	}
 	// other errors
-	hlog.SystemLogger().Errorf("Error=%s, remoteAddr=%s", err.Error(), rip)
+	hlog.SystemLogger().Errorf(hlog.EngineErrorFormat, err.Error(), rip)
 }
 
 func getRemoteAddrFromCloser(conn io.Closer) string {


Test patch:
diff --git a/pkg/app/server/hertz_test.go b/pkg/app/server/hertz_test.go
index aef7824..b9a07fb 100644
--- a/pkg/app/server/hertz_test.go
+++ b/pkg/app/server/hertz_test.go
@@ -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"
@@ -740,3 +741,43 @@ func TestOnprepare(t *testing.T) {
 	time.Sleep(time.Second)
 	c.Get(context.Background(), nil, "http://127.0.0.1:9231/ping")
 }
+
+type lockBuffer struct {
+	sync.Mutex
+	b bytes.Buffer
+}
+
+func (l *lockBuffer) Write(p []byte) (int, error) {
+	l.Lock()
+	defer l.Unlock()
+	return l.b.Write(p)
+}
+
+func (l *lockBuffer) String() string {
+	l.Lock()
+	defer l.Unlock()
+	return l.b.String()
+}
+
+func TestSilentMode(t *testing.T) {
+	hlog.SetSilentMode(true)
+	b := &lockBuffer{b: bytes.Buffer{}}
+
+	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())
+	}
+}
diff --git a/pkg/app/server/render/html_test.go b/pkg/app/server/render/html_test.go
index fb94458..eb8f36e 100644
--- a/pkg/app/server/render/html_test.go
+++ b/pkg/app/server/render/html_test.go
@@ -32,8 +32,8 @@ func TestHTMLDebug_StartChecker_timer(t *testing.T) {
 	}
 	render.startChecker()
 	select {
-	case <-time.After(render.RefreshInterval + 100*time.Millisecond):
-		t.Fatalf("should be triggered in 1 second")
+	case <-time.After(render.RefreshInterval + 500*time.Millisecond):
+		t.Fatalf("should be triggered in 1.5 second")
 	case <-render.reloadCh:
 	}
 }