Skip to content

Commit

Permalink
Pass host label when option is enabled
Browse files Browse the repository at this point in the history
  • Loading branch information
hussam-almarzoq committed Apr 28, 2024
1 parent 966aa12 commit 150d6fd
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions modules/caddyhttp/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var httpMetrics = struct {
func initHTTPMetrics() {
const ns, sub = "caddy", "http"

basicLabels := []string{"server", "handler"}
basicLabels := []string{"server", "handler", "host"}
httpMetrics.requestInFlight = promauto.NewGaugeVec(prometheus.GaugeOpts{
Namespace: ns,
Subsystem: sub,
Expand All @@ -59,7 +59,7 @@ func initHTTPMetrics() {
durationBuckets := prometheus.DefBuckets
sizeBuckets := prometheus.ExponentialBuckets(256, 4, 8)

httpLabels := []string{"server", "handler", "code", "method"}
httpLabels := []string{"server", "handler", "host", "code", "method"}
httpMetrics.requestDuration = promauto.NewHistogramVec(prometheus.HistogramOpts{
Namespace: ns,
Subsystem: sub,
Expand Down Expand Up @@ -103,23 +103,29 @@ func serverNameFromContext(ctx context.Context) string {
type metricsInstrumentedHandler struct {
handler string
mh MiddlewareHandler
perHost bool
}

func newMetricsInstrumentedHandler(handler string, mh MiddlewareHandler) *metricsInstrumentedHandler {
func newMetricsInstrumentedHandler(handler string, mh MiddlewareHandler, perHost bool) *metricsInstrumentedHandler {
httpMetrics.init.Do(func() {
initHTTPMetrics()
})

return &metricsInstrumentedHandler{handler, mh}
return &metricsInstrumentedHandler{handler, mh, perHost}
}

func (h *metricsInstrumentedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, next Handler) error {
host := "*"
if h.perHost {
host = r.Host
}

server := serverNameFromContext(r.Context())
labels := prometheus.Labels{"server": server, "handler": h.handler}
labels := prometheus.Labels{"server": server, "handler": h.handler, "host": host}
method := metrics.SanitizeMethod(r.Method)
// the "code" value is set later, but initialized here to eliminate the possibility
// of a panic
statusLabels := prometheus.Labels{"server": server, "handler": h.handler, "method": method, "code": ""}
statusLabels := prometheus.Labels{"server": server, "handler": h.handler, "host": host, "method": method, "code": ""}

inFlight := httpMetrics.requestInFlight.With(labels)
inFlight.Inc()
Expand All @@ -146,7 +152,7 @@ func (h *metricsInstrumentedHandler) ServeHTTP(w http.ResponseWriter, r *http.Re
// probably falling through with an empty handler.
if statusLabels["code"] == "" {
// we still sanitize it, even though it's likely to be 0. A 200 is
// returned on fallthrough so we want to reflect that.
// returned on fallthrough, so we want to reflect that.
statusLabels["code"] = metrics.SanitizeCode(status)
}

Expand Down

0 comments on commit 150d6fd

Please sign in to comment.