From d329dba63e4ccc42d609f016c4b52a49d1cebd43 Mon Sep 17 00:00:00 2001 From: Skyenought <1808644906@qq.com> Date: Wed, 23 Aug 2023 04:47:43 +0800 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20logger/middleware=20to=20E?= =?UTF-8?q?liminate=20Code=20Duplication?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/logger/logger.go | 49 ++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 28 deletions(-) diff --git a/middleware/logger/logger.go b/middleware/logger/logger.go index f33f3562a33..7ae0e1e95b9 100644 --- a/middleware/logger/logger.go +++ b/middleware/logger/logger.go @@ -139,40 +139,33 @@ func New(config ...Config) fiber.Handler { // Default output when no custom Format or io.Writer is given if cfg.Format == ConfigDefault.Format { - // Format error if exist + // Format error if it exists formatErr := "" - if cfg.enableColors { - if chainErr != nil { + if chainErr != nil { + if cfg.enableColors { formatErr = colors.Red + " | " + chainErr.Error() + colors.Reset - } - _, _ = buf.WriteString( //nolint:errcheck // This will never fail - fmt.Sprintf("%s |%s %3d %s| %13v | %15s |%s %-7s %s| %-"+errPaddingStr+"s %s\n", - timestamp.Load().(string), - statusColor(c.Response().StatusCode(), colors), c.Response().StatusCode(), colors.Reset, - data.Stop.Sub(data.Start), - c.IP(), - methodColor(c.Method(), colors), c.Method(), colors.Reset, - c.Path(), - formatErr, - ), - ) - } else { - if chainErr != nil { + } else { formatErr = " | " + chainErr.Error() } - _, _ = buf.WriteString( //nolint:errcheck // This will never fail - fmt.Sprintf("%s | %3d | %13v | %15s | %-7s | %-"+errPaddingStr+"s %s\n", - timestamp.Load().(string), - c.Response().StatusCode(), - data.Stop.Sub(data.Start), - c.IP(), - c.Method(), - c.Path(), - formatErr, - ), - ) } + // Construct the log format + logFormat := "%s |%s %3d %s| %7v | %15s |%s %-7s %s| %-" + errPaddingStr + "s %s\n" + if !cfg.enableColors { + logFormat = "%s | %3d | %7v | %15s | %-7s | %-" + errPaddingStr + "s %s\n" + } + + // Write log entry to buffer + _, _ = buf.WriteString(fmt.Sprintf(logFormat, + timestamp.Load().(string), + statusColor(c.Response().StatusCode(), colors), c.Response().StatusCode(), colors.Reset, + data.Stop.Sub(data.Start).Round(time.Millisecond), + c.IP(), + methodColor(c.Method(), colors), c.Method(), colors.Reset, + c.Path(), + formatErr, + )) //nolint:errcheck // This will never fail + // Write buffer to output _, _ = cfg.Output.Write(buf.Bytes()) //nolint:errcheck // This will never fail