Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🔥 Feature: Add AllLogger to Config #3153

Merged
merged 26 commits into from
Dec 1, 2024
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
3689da6
:fire: Feature: Add SetFlags to Logger Interface
haochunchang Oct 5, 2024
a32b80a
:rotating_light: Test: custom-defined Logger and LoggerFunc
haochunchang Oct 5, 2024
e609bbd
📚 Doc: add LoggerFunc and Logger to middleware logger
haochunchang Oct 5, 2024
fc80e6e
:rotating_light: Test: fine-tune custom Logger and LoggerFunc
haochunchang Oct 6, 2024
3afdcac
📚 Doc: add Logger documentation
haochunchang Oct 6, 2024
4fe7adf
:adhesive_bandage: fix: add default Logger field to default config
haochunchang Oct 10, 2024
ae18274
📚 Doc: remove Logger field in middleware logger
haochunchang Oct 14, 2024
ddb55f6
:rotating_light: Test: add tests for using fiber logger interface wra…
haochunchang Oct 14, 2024
eb093d5
📚 Doc: update custom logger example
haochunchang Nov 24, 2024
a88e612
Update docs/middleware/logger.md
ReneWerner87 Nov 29, 2024
8454f0c
update
efectn Nov 29, 2024
86c837d
update logger docs
efectn Nov 29, 2024
c872918
Merge branch 'main' into feature/logger-interface
efectn Nov 29, 2024
ed708f5
update what's new
efectn Nov 29, 2024
1a09cb6
replace setflags with getloggerinstance
efectn Nov 29, 2024
ef57ea3
fix linter
efectn Nov 29, 2024
2b2b5fe
update
efectn Nov 29, 2024
25f2952
Fix markdownlint issues
gaby Nov 30, 2024
6bbb4b9
apply reviews & improve coverage
efectn Dec 1, 2024
175ebf6
Merge branch 'feature/logger-interface' of https://github.com/haochun…
efectn Dec 1, 2024
c3a5a1e
fix linter
efectn Dec 1, 2024
353a2ff
Merge branch 'main' into feature/logger-interface
efectn Dec 1, 2024
d89b1cc
rename controllogger
efectn Dec 1, 2024
c99ee37
Merge branch 'feature/logger-interface' of https://github.com/haochun…
efectn Dec 1, 2024
3c27970
Update whats_new.md
ReneWerner87 Dec 1, 2024
8efa1b1
Merge branch 'main' into feature/logger-interface
ReneWerner87 Dec 1, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/api/log.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,3 +186,19 @@ commonLogger.Info("info")
```

Binding the logger to a context allows you to include context-specific information in your logs, improving traceability and debugging.

## Logger

You can use Logger to retrieve the logger instance. It is useful when you need to access underlying methods of the logger.
To retrieve the Logger instance, use the following method:

```go
logger := fiberlog.DefaultLogger() // Call DefaultLogger to get the default logger instance

stdlogger, ok := logger.Logger().(*log.Logger) // Get the logger instance and assert it to *log.Logger
if !ok {
panic("logger is not *log.Logger")
}

stdlogger.SetFlags(0) // Hide timestamp by setting flags to 0
```
40 changes: 40 additions & 0 deletions docs/middleware/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,44 @@ app.Use(logger.New(logger.Config{
}))
```

### Use Logger Middleware with Other Loggers

In order to use Fiber logger middleware with other loggers such as zerolog, zap, logrus; you can use `LoggerToWriter` helper which converts Fiber logger to a writer, which is compatible with the middleware.

```go
package main

import (
"github.com/gofiber/contrib/fiberzap/v2"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/log"
"github.com/gofiber/fiber/v3/middleware/logger"
)

func main() {
// Create a new Fiber instance
app := fiber.New()

// Create a new zap logger which is compatible with Fiber AllLogger interface
zap := fiberzap.NewLogger(fiberzap.LoggerConfig{
ExtraKeys: []string{"request_id"},
})

// Use the logger middleware with zerolog logger
app.Use(logger.New(logger.Config{
Output: logger.LoggerToWriter(zap, log.LevelDebug),
}))

// Define a route
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})

// Start server on http://localhost:3000
app.Listen(":3000")
}
```

:::tip
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.
:::
Expand All @@ -108,6 +146,7 @@ Writing to os.File is goroutine-safe, but if you are using a custom Output that
| TimeZone | `string` | TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc | `"Local"` |
| TimeInterval | `time.Duration` | TimeInterval is the delay before the timestamp is updated. | `500 * time.Millisecond` |
| Output | `io.Writer` | Output is a writer where logs are written. | `os.Stdout` |
| 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` |
efectn marked this conversation as resolved.
Show resolved Hide resolved
| DisableColors | `bool` | DisableColors defines if the logs output should be colorized. | `false` |
| enableColors | `bool` | Internal field for enabling colors in the log output. (This is not a user-configurable field) | - |
| enableLatency | `bool` | Internal field for enabling latency measurement in logs. (This is not a user-configurable field) | - |
Expand All @@ -125,6 +164,7 @@ var ConfigDefault = Config{
TimeInterval: 500 * time.Millisecond,
Output: os.Stdout,
DisableColors: false,
LoggerFunc: defaultLoggerInstance,
}
```

Expand Down
46 changes: 46 additions & 0 deletions docs/whats_new.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,12 @@ Here's a quick overview of the changes in Fiber `v3`:
- [🔄️ Redirect](#-redirect)
- [🌎 Client package](#-client-package)
- [🧰 Generic functions](#-generic-functions)
- [📃 Log](#-log)
- [🧬 Middlewares](#-middlewares)
- [CORS](#cors)
- [CSRF](#csrf)
- [Session](#session)
- [Logger](#logger)
- [Filesystem](#filesystem)
- [Monitor](#monitor)
- [Healthcheck](#healthcheck)
Expand Down Expand Up @@ -629,6 +631,12 @@ curl "http://localhost:3000/header"

</details>

## 📃 Log

`fiber.AllLogger` interface now has a new method called `Logger`. This method can be used to get the underlying logger instance from the Fiber logger middleware. This is useful when you want to configure the logger middleware with a custom logger and still want to access the underlying logger instance.

You can find more details about this feature in [/docs/api/log.md](./api/log.md#logger).

## 🧬 Middlewares

### Adaptor
Expand Down Expand Up @@ -704,6 +712,44 @@ The Session middleware has undergone key changes in v3 to improve functionality

For more details on these changes and migration instructions, check the [Session Middleware Migration Guide](./middleware/session.md#migration-guide).

### Logger

New helper function called `LoggerToWriter` has been added to the logger middleware. This function allows you to use 3rd party loggers such as `logrus` or `zap` with the Fiber logger middleware without any extra afford. For example, you can use `zap` with Fiber logger middleware like this:

```go
package main

import (
"github.com/gofiber/contrib/fiberzap/v2"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/log"
"github.com/gofiber/fiber/v3/middleware/logger"
)

func main() {
// Create a new Fiber instance
app := fiber.New()

// Create a new zap logger which is compatible with Fiber AllLogger interface
zap := fiberzap.NewLogger(fiberzap.LoggerConfig{
ExtraKeys: []string{"request_id"},
})

// Use the logger middleware with zerolog logger
app.Use(logger.New(logger.Config{
Output: logger.LoggerToWriter(zap, log.LevelDebug),
}))

// Define a route
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})

// Start server on http://localhost:3000
app.Listen(":3000")
}
```

### Filesystem

We've decided to remove filesystem middleware to clear up the confusion between static and filesystem middleware.
Expand Down
5 changes: 5 additions & 0 deletions log/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,11 @@ func (l *defaultLogger) SetOutput(writer io.Writer) {
l.stdlog.SetOutput(writer)
}

// Logger returns the logger instance. It can be used to adjust the logger configurations in case of need.
func (l *defaultLogger) Logger() any {
return l.stdlog
}

// DefaultLogger returns the default logger.
func DefaultLogger() AllLogger {
return logger
Expand Down
16 changes: 16 additions & 0 deletions log/default_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,22 @@ func Test_SetLevel(t *testing.T) {
require.Equal(t, "[?8] ", setLogger.level.toString())
}

func Test_Logger(t *testing.T) {
underlyingLogger := log.New(os.Stderr, "", log.LstdFlags|log.Lshortfile|log.Lmicroseconds)
setLogger := &defaultLogger{
stdlog: underlyingLogger,
depth: 4,
}

require.Equal(t, underlyingLogger, setLogger.Logger())

logger, ok := setLogger.Logger().(*log.Logger)
require.True(t, ok)

logger.SetFlags(log.LstdFlags | log.Lshortfile | log.Lmicroseconds)
require.Equal(t, log.LstdFlags|log.Lshortfile|log.Lmicroseconds, setLogger.stdlog.Flags())
}

func Test_Debugw(t *testing.T) {
initDefaultLogger()

Expand Down
10 changes: 10 additions & 0 deletions log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,25 @@ type CommonLogger interface {

// ControlLogger provides methods to config a logger.
type ControlLogger interface {
ReneWerner87 marked this conversation as resolved.
Show resolved Hide resolved
// SetLevel sets logging level.
//
// Available levels: Trace, Debug, Info, Warn, Error, Fatal, Panic.
SetLevel(level Level)

// SetOutput sets the logger output.
SetOutput(w io.Writer)

// Logger returns the logger instance. It can be used to adjust the logger configurations in case of need.
Logger() any
}

// AllLogger is the combination of Logger, FormatLogger, CtxLogger and ControlLogger.
// Custom extensions can be made through AllLogger
type AllLogger interface {
CommonLogger
ControlLogger

// WithContext returns a new logger with the given context.
WithContext(ctx context.Context) CommonLogger
}

Expand Down
106 changes: 106 additions & 0 deletions middleware/logger/logger_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//nolint:depguard // Because we test logging :D
package logger

import (
Expand All @@ -6,15 +7,18 @@ import (
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"runtime"
"strconv"
"sync"
"testing"
"time"

"github.com/gofiber/fiber/v3"
fiberlog "github.com/gofiber/fiber/v3/log"
"github.com/gofiber/fiber/v3/middleware/requestid"
"github.com/stretchr/testify/require"
"github.com/valyala/bytebufferpool"
Expand Down Expand Up @@ -181,6 +185,82 @@ func Test_Logger_ErrorTimeZone(t *testing.T) {
require.Equal(t, fiber.StatusNotFound, resp.StatusCode)
}

// go test -run Test_Logger_Fiber_Logger
func Test_Logger_LoggerToWriter(t *testing.T) {
t.Parallel()
app := fiber.New()

buf := bytebufferpool.Get()
defer bytebufferpool.Put(buf)

logger := fiberlog.DefaultLogger()
stdlogger, ok := logger.Logger().(*log.Logger)
require.True(t, ok)

stdlogger.SetFlags(0)
logger.SetOutput(buf)

testCases := []struct {
level fiberlog.Level
levelStr string
}{
{
level: fiberlog.LevelTrace,
levelStr: "Trace",
},
{
level: fiberlog.LevelDebug,
levelStr: "Debug",
},
{
level: fiberlog.LevelInfo,
levelStr: "Info",
},
{
level: fiberlog.LevelWarn,
levelStr: "Warn",
},
{
level: fiberlog.LevelError,
levelStr: "Error",
},
}

for _, tc := range testCases {
level := strconv.Itoa(int(tc.level))
t.Run(level, func(t *testing.T) {
buf.Reset()

app.Use("/"+level, New(Config{
Format: "${error}",
Output: LoggerToWriter(logger, tc.
level),
}))

app.Get("/"+level, func(_ fiber.Ctx) error {
return errors.New("some random error")
})

resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/"+level, nil))
require.NoError(t, err)
require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode)
require.Equal(t, "["+tc.levelStr+"] some random error\n", buf.String())
})

require.Panics(t, func() {
LoggerToWriter(logger, fiberlog.LevelPanic)
})

require.Panics(t, func() {
LoggerToWriter(logger, fiberlog.LevelFatal)
})

require.Panics(t, func() {
LoggerToWriter(nil, fiberlog.LevelFatal)
})
}
}

type fakeErrorOutput int

func (o *fakeErrorOutput) Write([]byte) (int, error) {
Expand Down Expand Up @@ -733,6 +813,19 @@ func Benchmark_Logger(b *testing.B) {
benchmarkSetup(bb, app, "/")
})

b.Run("DefaultFormatWithFiberLog", func(bb *testing.B) {
app := fiber.New()
logger := fiberlog.DefaultLogger()
logger.SetOutput(io.Discard)
app.Use(New(Config{
Output: LoggerToWriter(logger, fiberlog.LevelDebug),
}))
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})
benchmarkSetup(bb, app, "/")
})
ReneWerner87 marked this conversation as resolved.
Show resolved Hide resolved

b.Run("WithTagParameter", func(bb *testing.B) {
app := fiber.New()
app.Use(New(Config{
Expand Down Expand Up @@ -876,6 +969,19 @@ func Benchmark_Logger_Parallel(b *testing.B) {
benchmarkSetupParallel(bb, app, "/")
})

b.Run("DefaultFormatWithFiberLog", func(bb *testing.B) {
app := fiber.New()
logger := fiberlog.DefaultLogger()
logger.SetOutput(io.Discard)
app.Use(New(Config{
Output: LoggerToWriter(logger, fiberlog.LevelDebug),
}))
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, World!")
})
benchmarkSetupParallel(bb, app, "/")
})

b.Run("DefaultFormatDisableColors", func(bb *testing.B) {
app := fiber.New()
app.Use(New(Config{
Expand Down
Loading