Skip to content

Commit c0599ee

Browse files
JIeJaittgabycoderabbitai[bot]ReneWerner87
authored
πŸ”₯ feat: Add Skip function to logger middleware (#3333)
* πŸ”₯ Feature(logger): Add Filter option to logger middleware * πŸ“š Doc(logger): Clarify Filter middleware description * 🚨 Test(logger): Enhance logger filter test with parallel subtests * πŸ”’ Test(logger): Add mutex to prevent race conditions in logger test * πŸ”₯ Feature(logger): Add Filter option to logger middleware * πŸ“š Doc(logger): Clarify Filter middleware description * 🚨 Test(logger): Enhance logger filter test with parallel subtests * πŸ”’ Test(logger): Add mutex to prevent race conditions in logger test * 🚨 Test(logger): Refactor logger test to improve test isolation * Fix issue with unit-tests * Update middleware/logger/logger_test.go Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * Apply logger filter as soon as possible * πŸ“š Doc: Add logger filter configuration example to whats_new.md * πŸ“š Doc: Update logger filter documentation in whats_new.md * πŸ“š Doc: Update logger filter documentation and examples * 🩹 Fix: improve what_new.md * Update logic for Filter() in Logger middleware. Add more unit-tests * Rename fields to match expressjs/morgan * Update middleware/logger/default_logger.go --------- Co-authored-by: Juan Calderon-Perez <[email protected]> Co-authored-by: Juan Calderon-Perez <[email protected]> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> Co-authored-by: RW <[email protected]>
1 parent 1b26cf6 commit c0599ee

File tree

5 files changed

+243
-63
lines changed

5 files changed

+243
-63
lines changed

β€Ždocs/middleware/logger.md

+12-13
Original file line numberDiff line numberDiff line change
@@ -55,13 +55,13 @@ app.Use(logger.New(logger.Config{
5555
}))
5656

5757
// Custom File Writer
58-
file, err := os.OpenFile("./123.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
58+
accessLog, err := os.OpenFile("./access.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
5959
if err != nil {
60-
log.Fatalf("error opening file: %v", err)
60+
log.Fatalf("error opening access.log file: %v", err)
6161
}
62-
defer file.Close()
62+
defer accessLog.Close()
6363
app.Use(logger.New(logger.Config{
64-
Output: file,
64+
Stream: accessLog,
6565
}))
6666

6767
// Add Custom Tags
@@ -115,7 +115,7 @@ func main() {
115115

116116
// Use the logger middleware with zerolog logger
117117
app.Use(logger.New(logger.Config{
118-
Output: logger.LoggerToWriter(zap, log.LevelDebug),
118+
Stream: logger.LoggerToWriter(zap, log.LevelDebug),
119119
}))
120120

121121
// Define a route
@@ -129,7 +129,7 @@ func main() {
129129
```
130130

131131
:::tip
132-
Writing to os.File is goroutine-safe, but if you are using a custom Output that is not goroutine-safe, make sure to implement locking to properly serialize writes.
132+
Writing to os.File is goroutine-safe, but if you are using a custom Stream that is not goroutine-safe, make sure to implement locking to properly serialize writes.
133133
:::
134134

135135
## Config
@@ -138,31 +138,30 @@ Writing to os.File is goroutine-safe, but if you are using a custom Output that
138138

139139
| Property | Type | Description | Default |
140140
|:-----------------|:---------------------------|:---------------------------------------------------------------------------------------------------------------------------------|:----------------------------------------------------------------------|
141-
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
142-
| Done | `func(fiber.Ctx, []byte)` | Done is a function that is called after the log string for a request is written to Output, and pass the log string as parameter. | `nil` |
141+
| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` |
142+
| Skip | `func(fiber.Ctx) bool` | Skip is a function to determine if logging is skipped or written to Stream. | `nil` |
143+
| Done | `func(fiber.Ctx, []byte)` | Done is a function that is called after the log string for a request is written to Stream, and pass the log string as parameter. | `nil` |
143144
| CustomTags | `map[string]LogFunc` | tagFunctions defines the custom tag action. | `map[string]LogFunc` |
144145
| Format | `string` | Format defines the logging tags. | `[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}\n` |
145146
| TimeFormat | `string` | TimeFormat defines the time format for log timestamps. | `15:04:05` |
146147
| TimeZone | `string` | TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc | `"Local"` |
147148
| TimeInterval | `time.Duration` | TimeInterval is the delay before the timestamp is updated. | `500 * time.Millisecond` |
148-
| Output | `io.Writer` | Output is a writer where logs are written. | `os.Stdout` |
149+
| Stream | `io.Writer` | Stream is a writer where logs are written. | `os.Stdout` |
149150
| LoggerFunc | `func(c fiber.Ctx, data *Data, cfg Config) error` | Custom logger function for integration with logging libraries (Zerolog, Zap, Logrus, etc). Defaults to Fiber's default logger if not defined. | `see default_logger.go defaultLoggerInstance` |
150151
| DisableColors | `bool` | DisableColors defines if the logs output should be colorized. | `false` |
151-
| enableColors | `bool` | Internal field for enabling colors in the log output. (This is not a user-configurable field) | - |
152-
| enableLatency | `bool` | Internal field for enabling latency measurement in logs. (This is not a user-configurable field) | - |
153-
| timeZoneLocation | `*time.Location` | Internal field for the time zone location. (This is not a user-configurable field) | - |
154152

155153
## Default Config
156154

157155
```go
158156
var ConfigDefault = Config{
159157
Next: nil,
158+
Skip nil,
160159
Done: nil,
161160
Format: "[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}\n",
162161
TimeFormat: "15:04:05",
163162
TimeZone: "Local",
164163
TimeInterval: 500 * time.Millisecond,
165-
Output: os.Stdout,
164+
Stream: os.Stdout,
166165
DisableColors: false,
167166
LoggerFunc: defaultLoggerInstance,
168167
}

β€Ždocs/whats_new.md

+25
Original file line numberDiff line numberDiff line change
@@ -912,6 +912,31 @@ func main() {
912912

913913
</details>
914914

915+
The `Skip` is a function to determine if logging is skipped or written to `Stream`.
916+
917+
<details>
918+
<summary>Example Usage</summary>
919+
920+
```go
921+
app.Use(logger.New(logger.Config{
922+
Skip: func(c fiber.Ctx) bool {
923+
// Skip logging HTTP 200 requests
924+
return c.Response().StatusCode() == fiber.StatusOK
925+
},
926+
}))
927+
```
928+
929+
```go
930+
app.Use(logger.New(logger.Config{
931+
Skip: func(c fiber.Ctx) bool {
932+
// Only log errors, similar to an error.log
933+
return c.Response().StatusCode() < 400
934+
},
935+
}))
936+
```
937+
938+
</details>
939+
915940
### Filesystem
916941

917942
We've decided to remove filesystem middleware to clear up the confusion between static and filesystem middleware.

β€Žmiddleware/logger/config.go

+15-6
Original file line numberDiff line numberDiff line change
@@ -10,16 +10,21 @@ import (
1010

1111
// Config defines the config for middleware.
1212
type Config struct {
13-
// Output is a writer where logs are written
13+
// Stream is a writer where logs are written
1414
//
1515
// Default: os.Stdout
16-
Output io.Writer
16+
Stream io.Writer
1717

1818
// Next defines a function to skip this middleware when returned true.
1919
//
2020
// Optional. Default: nil
2121
Next func(c fiber.Ctx) bool
2222

23+
// Skip is a function to determine if logging is skipped or written to Stream.
24+
//
25+
// Optional. Default: nil
26+
Skip func(c fiber.Ctx) bool
27+
2328
// Done is a function that is called after the log string for a request is written to Output,
2429
// and pass the log string as parameter.
2530
//
@@ -98,12 +103,13 @@ type LogFunc func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (in
98103
// ConfigDefault is the default config
99104
var ConfigDefault = Config{
100105
Next: nil,
106+
Skip: nil,
101107
Done: nil,
102108
Format: defaultFormat,
103109
TimeFormat: "15:04:05",
104110
TimeZone: "Local",
105111
TimeInterval: 500 * time.Millisecond,
106-
Output: os.Stdout,
112+
Stream: os.Stdout,
107113
BeforeHandlerFunc: beforeHandlerFunc,
108114
LoggerFunc: defaultLoggerInstance,
109115
enableColors: true,
@@ -126,6 +132,9 @@ func configDefault(config ...Config) Config {
126132
if cfg.Next == nil {
127133
cfg.Next = ConfigDefault.Next
128134
}
135+
if cfg.Skip == nil {
136+
cfg.Skip = ConfigDefault.Skip
137+
}
129138
if cfg.Done == nil {
130139
cfg.Done = ConfigDefault.Done
131140
}
@@ -141,8 +150,8 @@ func configDefault(config ...Config) Config {
141150
if int(cfg.TimeInterval) <= 0 {
142151
cfg.TimeInterval = ConfigDefault.TimeInterval
143152
}
144-
if cfg.Output == nil {
145-
cfg.Output = ConfigDefault.Output
153+
if cfg.Stream == nil {
154+
cfg.Stream = ConfigDefault.Stream
146155
}
147156

148157
if cfg.BeforeHandlerFunc == nil {
@@ -154,7 +163,7 @@ func configDefault(config ...Config) Config {
154163
}
155164

156165
// Enable colors if no custom format or output is given
157-
if !cfg.DisableColors && cfg.Output == ConfigDefault.Output {
166+
if !cfg.DisableColors && cfg.Stream == ConfigDefault.Stream {
158167
cfg.enableColors = true
159168
}
160169

β€Žmiddleware/logger/default_logger.go

+10-4
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@ import (
1515

1616
// default logger for fiber
1717
func defaultLoggerInstance(c fiber.Ctx, data *Data, cfg Config) error {
18+
// Check if Skip is defined and call it.
19+
// Now, if Skip(c) == true, we SKIP logging:
20+
if cfg.Skip != nil && cfg.Skip(c) {
21+
return nil // Skip logging if Skip returns true
22+
}
23+
1824
// Alias colors
1925
colors := c.App().Config().ColorScheme
2026

@@ -91,7 +97,7 @@ func defaultLoggerInstance(c fiber.Ctx, data *Data, cfg Config) error {
9197
}
9298

9399
// Write buffer to output
94-
writeLog(cfg.Output, buf.Bytes())
100+
writeLog(cfg.Stream, buf.Bytes())
95101

96102
if cfg.Done != nil {
97103
cfg.Done(c, buf.Bytes())
@@ -125,7 +131,7 @@ func defaultLoggerInstance(c fiber.Ctx, data *Data, cfg Config) error {
125131
buf.WriteString(err.Error())
126132
}
127133

128-
writeLog(cfg.Output, buf.Bytes())
134+
writeLog(cfg.Stream, buf.Bytes())
129135

130136
if cfg.Done != nil {
131137
cfg.Done(c, buf.Bytes())
@@ -141,9 +147,9 @@ func defaultLoggerInstance(c fiber.Ctx, data *Data, cfg Config) error {
141147
func beforeHandlerFunc(cfg Config) {
142148
// If colors are enabled, check terminal compatibility
143149
if cfg.enableColors {
144-
cfg.Output = colorable.NewColorableStdout()
150+
cfg.Stream = colorable.NewColorableStdout()
145151
if os.Getenv("TERM") == "dumb" || os.Getenv("NO_COLOR") == "1" || (!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd())) {
146-
cfg.Output = colorable.NewNonColorable(os.Stdout)
152+
cfg.Stream = colorable.NewNonColorable(os.Stdout)
147153
}
148154
}
149155
}

0 commit comments

Comments
Β (0)