Skip to content

Commit fc7bf81

Browse files
committed
♻️: logger/middleware to Eliminate Code Duplication
1 parent 78f4510 commit fc7bf81

File tree

1 file changed

+21
-28
lines changed

1 file changed

+21
-28
lines changed

middleware/logger/logger.go

Lines changed: 21 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -139,40 +139,33 @@ func New(config ...Config) fiber.Handler {
139139

140140
// Default output when no custom Format or io.Writer is given
141141
if cfg.Format == ConfigDefault.Format {
142-
// Format error if exist
142+
// Format error if it exists
143143
formatErr := ""
144-
if cfg.enableColors {
145-
if chainErr != nil {
144+
if chainErr != nil {
145+
if cfg.enableColors {
146146
formatErr = colors.Red + " | " + chainErr.Error() + colors.Reset
147-
}
148-
_, _ = buf.WriteString( //nolint:errcheck // This will never fail
149-
fmt.Sprintf("%s |%s %3d %s| %7v | %15s |%s %-7s %s| %-"+errPaddingStr+"s %s\n",
150-
timestamp.Load().(string),
151-
statusColor(c.Response().StatusCode(), colors), c.Response().StatusCode(), colors.Reset,
152-
data.Stop.Sub(data.Start).Round(time.Millisecond),
153-
c.IP(),
154-
methodColor(c.Method(), colors), c.Method(), colors.Reset,
155-
c.Path(),
156-
formatErr,
157-
),
158-
)
159-
} else {
160-
if chainErr != nil {
147+
} else {
161148
formatErr = " | " + chainErr.Error()
162149
}
163-
_, _ = buf.WriteString( //nolint:errcheck // This will never fail
164-
fmt.Sprintf("%s | %3d | %7v | %15s | %-7s | %-"+errPaddingStr+"s %s\n",
165-
timestamp.Load().(string),
166-
c.Response().StatusCode(),
167-
data.Stop.Sub(data.Start).Round(time.Millisecond),
168-
c.IP(),
169-
c.Method(),
170-
c.Path(),
171-
formatErr,
172-
),
173-
)
174150
}
175151

152+
// Construct the log format
153+
logFormat := "%s |%s %3d %s| %7v | %15s |%s %-7s %s| %-" + errPaddingStr + "s %s\n"
154+
if !cfg.enableColors {
155+
logFormat = "%s | %3d | %7v | %15s | %-7s | %-" + errPaddingStr + "s %s\n"
156+
}
157+
158+
// Write log entry to buffer
159+
_, _ = buf.WriteString(fmt.Sprintf(logFormat,
160+
timestamp.Load().(string),
161+
statusColor(c.Response().StatusCode(), colors), c.Response().StatusCode(), colors.Reset,
162+
data.Stop.Sub(data.Start).Round(time.Millisecond),
163+
c.IP(),
164+
methodColor(c.Method(), colors), c.Method(), colors.Reset,
165+
c.Path(),
166+
formatErr,
167+
))
168+
176169
// Write buffer to output
177170
_, _ = cfg.Output.Write(buf.Bytes()) //nolint:errcheck // This will never fail
178171

0 commit comments

Comments
 (0)