route/internal/middleware/trace.go

45 lines
939 B
Go
Raw Permalink Normal View History

2017-10-01 13:54:56 +00:00
package middleware
import (
"context"
"net/http"
"path/filepath"
"time"
"github.com/Xe/ln"
"golang.org/x/net/trace"
)
// Trace adds go stdlib tracing to this http handler.
2018-01-21 16:22:10 +00:00
func Trace(family string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sp := trace.New(filepath.Base(family), r.Host+r.RequestURI)
defer sp.Finish()
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
2017-10-01 13:54:56 +00:00
2018-01-21 16:22:10 +00:00
ctx = trace.NewContext(ctx, sp)
f := ln.F{
"family": family,
"method": r.Method,
"path": r.URL.Path,
"remote_addr": r.RemoteAddr,
"user_agent": r.UserAgent(),
}
ctx = ln.WithF(ctx, f)
2017-10-01 13:54:56 +00:00
2018-01-21 16:22:10 +00:00
next.ServeHTTP(w, r.WithContext(ctx))
2017-10-01 13:54:56 +00:00
2018-01-21 16:22:10 +00:00
ws, ok := w.(interface {
Status() int
})
if ok {
f["status"] = ws.Status()
}
2017-10-01 13:54:56 +00:00
2018-01-21 16:22:10 +00:00
ln.Log(ctx, f)
})
}
2017-10-01 13:54:56 +00:00
}