Skip to content

Commit

Permalink
Improve logger docs with slog example
Browse files Browse the repository at this point in the history
  • Loading branch information
aldas committed Nov 10, 2023
1 parent af7ae6b commit fb43007
Showing 1 changed file with 28 additions and 2 deletions.
30 changes: 28 additions & 2 deletions website/docs/middleware/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Echo has 2 different logger middlewares:
- Older string template based logger [`Logger`](https://github.com/labstack/echo/blob/master/middleware/logger.go) - easy to start with but has limited capabilities
- Newer customizable function based logger [`RequestLogger`](https://github.com/labstack/echo/blob/master/middleware/request_logger.go) - allows developer fully to customize what is logged and how it is logged. Suitable for usage with 3rd party logger libraries.

## String Template
## Old Logger middleware (string template)

## Usage

Expand Down Expand Up @@ -106,7 +106,7 @@ DefaultLoggerConfig = LoggerConfig{
}
```

## Customizable Function
# New RequestLogger middleware (customizable Function)

RequestLogger middleware allows developer fully to customize what is logged and how it is logged and is more suitable
for usage with 3rd party (structured logging) libraries.
Expand All @@ -132,6 +132,32 @@ e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
}))
```

Example for slog (https://pkg.go.dev/log/slog)
```go
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
e.Use(middleware.RequestLoggerWithConfig(middleware.RequestLoggerConfig{
LogStatus: true,
LogURI: true,
LogError: true,
HandleError: true, // forwards error to the global error handler, so it can decide appropriate status code
LogValuesFunc: func(c echo.Context, v middleware.RequestLoggerValues) error {
if v.Error == nil {
logger.LogAttrs(context.Background(), slog.LevelInfo, "REQUEST",
slog.String("uri", v.URI),
slog.Int("status", v.Status),
)
} else {
logger.LogAttrs(context.Background(), slog.LevelError, "REQUEST_ERROR",
slog.String("uri", v.URI),
slog.Int("status", v.Status),
slog.String("err", v.Error.Error()),
)
}
return nil
},
}))
```

Example for Zerolog (https://github.com/rs/zerolog)
```go
logger := zerolog.New(os.Stdout)
Expand Down

0 comments on commit fb43007

Please sign in to comment.