package api import ( "fmt" "log/slog" "strings" "time" "github.com/gin-gonic/gin" ) // slowPage is when a console page logs how long its steps took. const slowPage = time.Second // stepTimer measures the steps of a request. It reports them to the // browser in a Server-Timing header and, when the request was slow, in // the log. type stepTimer struct { start, last time.Time steps []step } type step struct { name string d time.Duration } func newStepTimer() *stepTimer { now := time.Now() return &stepTimer{start: now, last: now} } // done ends the step name. func (t *stepTimer) done(name string) { now := time.Now() t.steps = append(t.steps, step{name, now.Sub(t.last)}) t.last = now } // header sets the Server-Timing header of the steps so far; call it // before the body is written. func (t *stepTimer) header(c *gin.Context) { parts := make([]string, len(t.steps)) for i, s := range t.steps { parts[i] = fmt.Sprintf("%s;dur=%.1f", s.name, float64(s.d.Microseconds())/1000) } c.Header("Server-Timing", strings.Join(parts, ", ")) } // logIfSlow logs the steps when the request took slowPage or longer. func (t *stepTimer) logIfSlow(c *gin.Context, log *slog.Logger) { total := time.Since(t.start) if total < slowPage { return } attrs := []any{"path", c.Request.URL.Path, "total_ms", total.Milliseconds()} for _, s := range t.steps { attrs = append(attrs, s.name+"_ms", s.d.Milliseconds()) } log.WarnContext(c.Request.Context(), "slow console page", attrs...) }