Documentation
¶
Overview ¶
Access logging: one structured record per request, with your own fields.
accesslog.New(w) writes to any io.Writer (accesslog.File(path) and accesslog.FileUnbuffered(path) open a file instead). SetFormatter picks the output shape - &accesslog.JSON{}, &accesslog.CSV{} or &accesslog.Template{Text: "..."}; without one the default pipe-delimited text format is used. AddFields attaches values extracted from every request, and accesslog.GetFields(ctx) lets a single handler add its own.
Register the middleware with UseRouter so 404s and 405s are recorded too, and Close it on shutdown to flush buffered output.
Learn: write one structured log record per request, add your own fields from middleware or a handler, and skip noisy endpoints. Before: ../request-id
Run:
go run main.go
Try:
curl http://localhost:8080/ # 200, one JSON log line
curl -X POST http://localhost:8080/orders -d '{"sku":"IRIS-14"}' # 201, the log line carries order_id
curl http://localhost:8080/health # 200, skipped: no log line
curl http://localhost:8080/nope # 404, still logged
Next: ../cache