https://github.com/lestrrat-go/accesslog
HTTP middleware to log access logs based on `log/slog` for Go
https://github.com/lestrrat-go/accesslog
Last synced: 4 months ago
JSON representation
HTTP middleware to log access logs based on `log/slog` for Go
- Host: GitHub
- URL: https://github.com/lestrrat-go/accesslog
- Owner: lestrrat-go
- License: mit
- Created: 2024-10-12T07:57:33.000Z (9 months ago)
- Default Branch: main
- Last Pushed: 2024-10-12T08:05:52.000Z (9 months ago)
- Last Synced: 2025-01-09T03:41:40.225Z (6 months ago)
- Language: Go
- Size: 11.7 KB
- Stars: 1
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# github.com/lestrrat-go/accesslog  [](https://pkg.go.dev/github.com/lestrrat-go/accesslog)
`github.com/lestrrat-go/accesslog` provides an HTTP middleware that logs accesslogs based on `log/slog`.
# SYNOPSIS
```go
package accesslog_testimport (
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"time""github.com/lestrrat-go/accesslog"
)func Example() {
al := accesslog.New().
// Set the clock to a static time to force duration=0 for testing
Clock(accesslog.StaticClock(time.Time{})).
Logger(
slog.New(
slog.NewJSONHandler(os.Stdout,
&slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
switch a.Key {
case slog.TimeKey:
// replace time to get static output for testing
return slog.Time(slog.TimeKey, time.Time{})
case "remote_addr":
// replace value to get static output for testing
return slog.String("remote_addr", "127.0.0.1:99999")
}
return a
},
},
),
),
)srv := httptest.NewServer(al.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("Hello, World!"))
})))
defer srv.Close()_, err := http.Get(srv.URL)
if err != nil {
fmt.Println(err.Error())
return
}// OUTPUT:
// {"time":"0001-01-01T00:00:00Z","level":"INFO","msg":"access","remote_addr":"127.0.0.1:99999","http_method":"GET","path":"/","status":200,"body_bytes_sent":13,"http_referer":"","http_user_agent":"Go-http-client/1.1"}
}
```
source: [accesslog_example_test.go](https://github.com/lestrrat-go/accesslog/blob/refs/heads/main/accesslog_example_test.go)