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 May 1, 2024
1 parent 368b156 commit 4ec4272
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 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 {
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": ""}

if h.perHost {
labels["host"] = r.Host
statusLabels["host"] = r.Host
}

inFlight := httpMetrics.requestInFlight.With(labels)
inFlight.Inc()
Expand Down

0 comments on commit 4ec4272

Please sign in to comment.