From 6040638a2649afa585d4ad55fd68f89afe00a47a Mon Sep 17 00:00:00 2001 From: mstmdev Date: Fri, 25 Mar 2022 16:59:19 +0800 Subject: [PATCH] Add test for logger --- logger.go | 6 ++---- logger_test.go | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/logger.go b/logger.go index 67ca6399..bdf158c8 100644 --- a/logger.go +++ b/logger.go @@ -38,7 +38,7 @@ var consoleColorMode = autoColor // LoggerConfig defines the config for Logger middleware. type LoggerConfig struct { - // Optional. Default value is gin.defaultLogFormatter + // Formatter is optional, the default value is gin.defaultLogFormatter Formatter LogFormatter // Output is a writer where logs are written. @@ -265,9 +265,7 @@ func LoggerWithConfig(conf LoggerConfig) HandlerFunc { param.Path = path - if _, err := out.Write(bytesconv.StringToBytes(formatter(param))); err != nil { - fmt.Println(err) - } + out.Write(bytesconv.StringToBytes(formatter(param))) } } } diff --git a/logger_test.go b/logger_test.go index da1b654e..8d1beebe 100644 --- a/logger_test.go +++ b/logger_test.go @@ -147,6 +147,15 @@ func TestLoggerWithConfig(t *testing.T) { assert.Contains(t, buffer.String(), "/notfound") } +func TestLoggerWithConfigWriteError(t *testing.T) { + w := &mockErrWriter{} + router := New() + router.Use(LoggerWithConfig(LoggerConfig{Output: w})) + router.GET("/example", func(c *Context) {}) + PerformRequest(router, "GET", "/example?a=100") + assert.True(t, w.triggerErrorWrite) +} + func TestLoggerWithFormatter(t *testing.T) { buffer := new(bytes.Buffer) @@ -432,3 +441,12 @@ func TestForceConsoleColor(t *testing.T) { // reset console color mode. consoleColorMode = autoColor } + +type mockErrWriter struct { + triggerErrorWrite bool +} + +func (w *mockErrWriter) Write(p []byte) (n int, err error) { + w.triggerErrorWrite = true + return 0, errors.New("test error writer") +}