http_metrics

package
v1.67.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 6 Imported by: 0

README

Package http_metrics

Пакет http_metrics предоставляет инструменты для сбора и регистрации метрик HTTP-клиента и HTTP-сервера с использованием Prometheus.

Types

ClientStorage

Хранилище метрик HTTP-клиента.

Metrics:

client_request_duration_ms

Общая продолжительность запроса.

client_connect_duration

Продолжительность установления соединения.

client_request_write_duration

Продолжительность записи запроса.

client_dns_duration

Продолжительность DNS-запроса.

client_response_read_duration

Продолжительность чтения ответа.

client_status_code_count

Счётчик HTTP-кодов.

client_error_count

Счётчик ошибок клиента.

Methods:

func NewClientStorage(reg *metrics.Registry) *ClientStorage

Создаёт новое хранилище метрик для HTTP-клиента.

func (s *ClientStorage) ObserveDuration(endpoint string, duration time.Duration)

Регистрирует общую задержку запроса.

func (s *ClientStorage) ObserveConnEstablishment(endpoint string, duration time.Duration)

Регистрирует задержку установления соединения.

func (s *ClientStorage) ObserveRequestWriting(endpoint string, duration time.Duration)

Регистрирует продолжительность записи запроса.

func (s *ClientStorage) ObserveDnsLookup(endpoint string, duration time.Duration)

Регистрирует задержку DNS-запроса.

func (s *ClientStorage) ObserveResponseReading(endpoint string, duration time.Duration)

Регистрирует продолжительность чтения ответа.

func (s *ClientStorage) CountStatusCode(endpoint string, code int)

Увеличивает счётчик HTTP-кодов ответа.

func (s *ClientStorage) CountError(endpoint string, err error)

Увеличивает счётчик ошибок клиента с маскированием URL/IP.

func ClientEndpointToContext(ctx context.Context, endpoint string) context.Context

Сохраняет endpoint клиента в контекст.

func ClientEndpoint(ctx context.Context) string

Извлекает endpoint клиента из контекста.

ServerStorage

Хранилище метрик HTTP-сервера

Metrics:

request_duration_ms

Продолжительность запроса.

request_body_size

Размер тела запроса.

response_body_size

Размер тела ответа.

status_code_count

Счётчик HTTP-кодов.

Methods:

func NewServerStorage(reg *metrics.Registry) *ServerStorage

Создаёт новое хранилище метрик для HTTP-сервера.

func (s *ServerStorage) ObserveDuration(method string, endpoint string, duration time.Duration)

Регистрирует задержку запроса.

func (s *ServerStorage) ObserveRequestBodySize(method string, endpoint string, size int)

Регистрирует размер тела запроса.

func (s *ServerStorage) ObserveResponseBodySize(method string, endpoint string, size int)

Регистрирует размер тела ответа.

func (s *ServerStorage) CountStatusCode(method string, endpoint string, code int)

Увеличивает счётчик HTTP-кодов ответа.

func ServerEndpointToContext(ctx context.Context, endpoint string) context.Context

Сохраняет endpoint сервера в контекст.

func ServerEndpoint(ctx context.Context) string

Извлекает endpoint сервера из контекста.

Prometheus metrics example

# HELP client_request_duration_ms The total duration of HTTP client requests
# TYPE client_request_duration_ms summary
client_request_duration_ms{endpoint="external-service"} 123.4

# HELP client_connect_duration The duration of connection establishment
# TYPE client_connect_duration summary
client_connect_duration{endpoint="external-service"} 12.3

# HELP client_request_write_duration The duration of writing the request
# TYPE client_request_write_duration summary
client_request_write_duration{endpoint="external-service"} 8.7

# HELP client_dns_duration The duration of DNS lookup
# TYPE client_dns_duration summary
client_dns_duration{endpoint="external-service"} 5.6

# HELP client_response_read_duration The duration of reading the response
# TYPE client_response_read_duration summary
client_response_read_duration{endpoint="external-service"} 17.2

# HELP client_status_code_count Count of HTTP response status codes
# TYPE client_status_code_count counter
client_status_code_count{endpoint="external-service",code="200"} 42

# HELP client_error_count Count of client errors
# TYPE client_error_count counter
client_error_count{endpoint="external-service",error="connection_timeout"} 3

# HELP request_duration_ms The total duration of HTTP server requests
# TYPE request_duration_ms summary
request_duration_ms{method="GET",endpoint="/api/resource"} 110.5

# HELP request_body_size Size of the HTTP request body
# TYPE request_body_size summary
request_body_size{method="GET",endpoint="/api/resource"} 512

# HELP response_body_size Size of the HTTP response body
# TYPE response_body_size summary
response_body_size{method="GET",endpoint="/api/resource"} 1024

# HELP status_code_count Count of HTTP response status codes (server)
# TYPE status_code_count counter
status_code_count{method="GET",endpoint="/api/resource",code="200"} 58

Usage

Client
clientMetrics := http_metrics.NewClientStorage(metrics.DefaultRegistry)
...
clientMetrics.ObserveDuration("external-service", duration)
Server
serverMetrics := http_metrics.NewServerStorage(metrics.DefaultRegistry)
...
serverMetrics.ObserveDuration("GET", "/api/resource", duration)

Documentation

Overview

Package http_metrics provides Prometheus metric collectors for HTTP server and client operations. It tracks request latencies, body sizes, status codes, and error counts for both incoming HTTP requests and outgoing HTTP client calls.

Example usage for HTTP server:

reg := metrics.NewRegistry()
serverStorage := http_metrics.NewServerStorage(reg)

// In your HTTP handler:
start := time.Now()
// ... handle request ...
serverStorage.ObserveDuration(method, endpoint, time.Since(start))
serverStorage.CountStatusCode(method, endpoint, statusCode)

Example usage for HTTP client:

clientStorage := http_metrics.NewClientStorage(reg)
clientStorage.ObserveDuration(endpoint, duration)
clientStorage.CountError(endpoint, err)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClientEndpoint

func ClientEndpoint(ctx context.Context) string

ClientEndpoint retrieves the HTTP client endpoint name from the context. Returns an empty string if no endpoint was set.

func ClientEndpointToContext

func ClientEndpointToContext(ctx context.Context, endpoint string) context.Context

ClientEndpointToContext stores the HTTP client endpoint name in the context.

func ServerEndpoint

func ServerEndpoint(ctx context.Context) string

ServerEndpoint retrieves the HTTP endpoint name from the context. Returns an empty string if no endpoint was set.

func ServerEndpointToContext

func ServerEndpointToContext(ctx context.Context, endpoint string) context.Context

ServerEndpointToContext stores the HTTP endpoint name in the context. This is useful for passing endpoint information through middleware chains.

Types

type ClientStorage

type ClientStorage struct {
	// contains filtered or unexported fields
}

ClientStorage collects metrics for HTTP client operations, including request latency, connection establishment, DNS lookup, and error counts.

func NewClientStorage

func NewClientStorage(reg *metrics.Registry) *ClientStorage

NewClientStorage creates a new ClientStorage instance and registers its metrics with the provided registry. Metrics are labeled by the client endpoint.

func (*ClientStorage) CountError added in v1.45.2

func (s *ClientStorage) CountError(endpoint string, err error)

CountError increments the error counter for a specific error type. The error message is sanitized to remove sensitive information like URLs and IPs.

func (*ClientStorage) CountStatusCode added in v1.45.2

func (s *ClientStorage) CountStatusCode(endpoint string, code int)

CountStatusCode increments the counter for a specific HTTP status code.

func (*ClientStorage) ObserveConnEstablishment added in v1.38.0

func (s *ClientStorage) ObserveConnEstablishment(endpoint string, duration time.Duration)

ObserveConnEstablishment records the time taken to establish a connection.

func (*ClientStorage) ObserveDnsLookup added in v1.38.0

func (s *ClientStorage) ObserveDnsLookup(endpoint string, duration time.Duration)

ObserveDnsLookup records the time taken for DNS resolution.

func (*ClientStorage) ObserveDuration

func (s *ClientStorage) ObserveDuration(endpoint string, duration time.Duration)

ObserveDuration records the total duration of an HTTP client request.

func (*ClientStorage) ObserveRequestWriting added in v1.38.0

func (s *ClientStorage) ObserveRequestWriting(endpoint string, duration time.Duration)

ObserveRequestWriting records the time taken to write the request body.

func (*ClientStorage) ObserveResponseReading added in v1.38.0

func (s *ClientStorage) ObserveResponseReading(endpoint string, duration time.Duration)

ObserveResponseReading records the time taken to read the response.

type ServerStorage

type ServerStorage struct {
	// contains filtered or unexported fields
}

ServerStorage collects metrics for HTTP server operations, including request latency, request/response body sizes, and HTTP status code counts.

func NewServerStorage

func NewServerStorage(reg *metrics.Registry) *ServerStorage

NewServerStorage creates a new ServerStorage instance and registers its metrics with the provided registry. The metrics are labeled by HTTP method and endpoint.

func (*ServerStorage) CountStatusCode

func (s *ServerStorage) CountStatusCode(method string, endpoint string, code int)

CountStatusCode increments the counter for a specific HTTP status code, labeled by method, endpoint, and status code.

func (*ServerStorage) ObserveDuration

func (s *ServerStorage) ObserveDuration(method string, endpoint string, duration time.Duration)

ObserveDuration records the latency of an HTTP request, labeled by method and endpoint.

func (*ServerStorage) ObserveRequestBodySize

func (s *ServerStorage) ObserveRequestBodySize(method string, endpoint string, size int)

ObserveRequestBodySize records the size of an HTTP request body in bytes.

func (*ServerStorage) ObserveResponseBodySize

func (s *ServerStorage) ObserveResponseBodySize(method string, endpoint string, size int)

ObserveResponseBodySize records the size of an HTTP response body in bytes.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL