Merge 8dbee163b27a5202c73a920d79129edf179de444 into a481ee2897af1e368de5c919fbeb21b89aa26fc7

This commit is contained in:
mstmdev 2023-09-28 07:07:32 +08:00 committed by GitHub
commit 3e501869c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 2 deletions

View File

@ -11,6 +11,7 @@ import (
"os"
"time"
"github.com/gin-gonic/gin/internal/bytesconv"
"github.com/mattn/go-isatty"
)
@ -37,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.
@ -266,7 +267,9 @@ func LoggerWithConfig(conf LoggerConfig) HandlerFunc {
param.Path = path
fmt.Fprint(out, formatter(param))
if _, err := out.Write(bytesconv.StringToBytes(formatter(param))); err != nil {
debugPrintError(err)
}
}
}
}

View File

@ -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(strings.Builder)
@ -434,3 +443,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")
}