metrics4gin

package module
v1.0.13 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Metrics for Gin

PkgGoDev

Metric Middleware for gin framework with request counters for Prometheus/Victoria Metrics time-series databases. Push and pull (via scrapper endpoint) mechanisms are supported

Metrics recorded

These counters are recorded, tagged with method, uri and status code:

  • gin_request_total{method=%q,uri=%q,status="%v"} - integer - total number of HTTP requests served.
  • gin_request_duration_ms{method=%q,uri=%q,status="%v"} - float - counter for duration of requests in milliseconds.
  • gin_request_bytes_written{method=%q,uri=%q,status="%v"} - integer - counter for bytes written as responses.
  • gin_request_bytes_read{method=%q,uri=%q,status="%v"} - integer - counter for bytes read as requests body.

Example

See main.go for full working example.

Basically:

package main

import (
	"context"
    "time"
	
	"github.com/gin-gonic/gin"
	"github.com/vodolaz095/metrics4gin"
)

func main() {
	engine := gin.Default()
	metricsHandler := metrics4gin.NewWithDefaultMetricsSet()

	// tune metrics handler by setting parameters
	metricsHandler.Endpoint = metrics4gin.DefaultEndpoint
	// enable exposing default golang runtime metrics on scrapper endpoint
	metricsHandler.ExposeRuntimeMetrics = true
	// headers to be send with every request for pushing data in Victoria Metrics/Prometheus
	metricsHandler.ExtraHeaders["Authorization"] = "Basic dGVzdDp0ZXN0Cg==" // test:test
	// extra labels to be added to all metrics send to Victoria Metrics/Prometheus
	metricsHandler.ExtraLabels["job"] = "example_metrics4gin"
	metricsHandler.ExtraLabels["instance"] = "server.local"
	// usually, victoria metrics expects POST requests for accepting metrics, but it can be changed to GET
	metricsHandler.Method = http.MethodPost 

	// inject middleware into gin engine
	metricsHandler.InjectMiddleware(engine)

    // expose other endpoints
    // ...
	
	// expose prometheus compatible scrapper endpoint
	engine.GET("/metrics", metricsHandler.ExposeMetrics) 

	// periodically push metrics to victoria metrics database
	go metricsHandler.StartPushing(context.Background(), 10*time.Second)

	// start http server
	engine.Run("0.0.0.0:3000")
}


MIT License

Copyright (c) 2025 Остроумов Анатолий

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

View Source
const DefaultEndpoint = "http://localhost:8428/api/v1/import/prometheus"

DefaultEndpoint is default endpoint to send metrics too

View Source
const DefaultMetricsEndpointRelativePath = "/metrics"

DefaultMetricsEndpointRelativePath is usual path to expose metrics for Prometheus scrappers

Variables

This section is empty.

Functions

This section is empty.

Types

type Handler

type Handler struct {
	// MetricSet is
	MetricSet *metrics.Set
	// ExposeRuntimeMetrics toggles exposing default golang runtime metrics at scrapper endpoint
	ExposeRuntimeMetrics bool
	// ExtraLabels are added to all metrics being sent via PUSH mechanism into Prometheus/Victoria Metrics database
	ExtraLabels map[string]string
	// ExtraHeaders are added to HTTP requests being sent
	ExtraHeaders map[string]string
	// Endpoint sets destination for metrics, by default it is  DefaultEndpoint
	Endpoint string
	// Method defines http method used to deliver metrics, default is http.MethodGet
	Method string
}

Handler stores logic in it

func NewWithDefaultMetricsSet

func NewWithDefaultMetricsSet() *Handler

NewWithDefaultMetricsSet creates new Handler with default golang runtime metrics set

func NewWithEmptyMetricsSet

func NewWithEmptyMetricsSet() *Handler

NewWithEmptyMetricsSet creates new Handler with empty metrics set

func (*Handler) ExposeMetrics

func (h *Handler) ExposeMetrics(c *gin.Context)

ExposeMetrics expose metrics endpoint

func (*Handler) InjectMiddleware

func (h *Handler) InjectMiddleware(engine *gin.Engine)

InjectMiddleware injects middleware into gin.Engine that counts requests

func (*Handler) StartPushing

func (h *Handler) StartPushing(ctx context.Context, interval time.Duration) error

StartPushing starts pushing handler metrics into Victoria/Prometheus

func (*Handler) StartPushingDefaultMetrics

func (h *Handler) StartPushingDefaultMetrics(ctx context.Context, interval time.Duration) error

StartPushingDefaultMetrics starts pushing default (including runtime with 'process_*' and `go_*` if Handler.ExposeRuntimeMetrics enabled) metrics into Victoria/Prometheus

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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