You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

基本介绍

监控指标的代码开发直接使用框架主库的gmetric组件即可,但由于gmetric组件实际上只是定义了监控指标的相关接口,并且默认提供的NoopPerformer,默认监控指标特性是关闭的。因此需要引入具体的接口实现组件才能真正开启监控指标特性。框架社区提供了社区组件github.com/gogf/gf/contrib/metric/otelmetric/v2,使用了OpenTelemetry实现框架的监控指标接口,引入该社区组件即可开启监控指标特性。otelmetric组件源码地址:https://github.com/gogf/gf/tree/master/contrib/metric/otelmetric

使用示例

我们来看一个简单的监控指标实现示例。

package main

import (
	"go.opentelemetry.io/otel/sdk/metric"
	"go.opentelemetry.io/otel/sdk/metric/metricdata"

	"github.com/gogf/gf/contrib/metric/otelmetric/v2"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gmetric"
)

var (
	meter = gmetric.GetGlobalProvider().Meter(gmetric.MeterOption{
		Instrument:        "github.com/gogf/gf/example/metric/basic",
		InstrumentVersion: "v1.0",
	})
	counter = meter.MustCounter(
		"goframe.metric.demo.counter",
		gmetric.MetricOption{
			Help: "This is a simple demo for Counter usage",
			Unit: "bytes",
		},
	)
)

func main() {
	var (
		ctx    = gctx.New()
		reader = metric.NewManualReader()
	)

	provider := otelmetric.MustProvider(metric.WithReader(reader))
	provider.SetAsGlobal()
	defer provider.Shutdown(ctx)

	counter.Inc(ctx)
	counter.Add(ctx, 10)

	var (
		rm  = metricdata.ResourceMetrics{}
		err = reader.Collect(ctx, &rm)
	)
	if err != nil {
		g.Log().Fatal(ctx, err)
	}
	g.DumpJson(rm)
}













Content Menu

  • No labels