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