DEV Community

li-jin-ou
li-jin-ou

Posted on

Hertz how to use Opentelemetry for beginners

Introduction

In the previous article we focused on the use of hlog in conjunction with requestid to associate logs.
Hertz now also provides extended support for Opentelemetry obs-opentelemetry to facilitate the use of Opentelemetry in the Hertz service.

How to use

The Opentelemetry extension to Hertz provides three main functions: Metric, Tracing and Logging.

Metric

Use Opentelemetry's Metric at Hertz.

It supports HTTP Metrics and Runtime Metrics, more details can be found here.

import (
    "github.com/hertz-contrib/obs-opentelemetry/provider"
    hertztracing "github.com/hertz-contrib/obs-opentelemetry/tracing"
)

func main() {
    // ...
  p := provider.NewOpenTelemetryProvider(
            provider.WithServiceName(serviceName), 
            // Support setting ExportEndpoint via environment variables: OTEL_EXPORTER_OTLP_ENDPOINT 
            provider.WithExportEndpoint("localhost:4317"),
            provider.WithInsecure(), 
    )
    defer p.Shutdown(context.Background())
    tracer, cfg := hertztracing.NewServerTracer()
    h := server.Default(tracer)
    h.Use(hertztracing.ServerMiddleware(cfg))
    // ...
}

Enter fullscreen mode Exit fullscreen mode

The results are as follows:

Image description

Tracing

Hertz integrates with Opentelemetry's tracing.

import (
    ...
    "github.com/hertz-contrib/obs-opentelemetry/provider"
    "github.com/hertz-contrib/obs-opentelemetry/tracing"
)


func main()  {
    serviceName := "echo"

    p := provider.NewOpenTelemetryProvider(
        provider.WithServiceName(serviceName),
        provider.WithExportEndpoint("localhost:4317"),
        provider.WithInsecure(),
    )
    defer p.Shutdown(context.Background())

    tracer, cfg := hertztracing.NewServerTracer()
    h := server.Default(tracer)
    h.Use(hertztracing.ServerMiddleware(cfg))

    ...

    h.Spin()
}

Enter fullscreen mode Exit fullscreen mode

The results are as follows:

Image description

Logger

Hertz provides logger for association with tracing.

import (
    hertzlogrus "github.com/hertz-contrib/obs-opentelemetry/logging/logrus"
)

func init()  {
    hlog.SetLogger(hertzlogrus.NewLogger())
    hlog.SetLevel(hlog.LevelDebug)

}

func main() {
    //...
    h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
        req := &api.Request{Message: "my request"}
        resp, err := client.Echo(c, req)
        if err != nil {
            hlog.Errorf(err.Error())
            return
        }
        hlog.CtxDebugf(c, "message received successfully: %s", req.Message)
        ctx.JSON(consts.StatusOK, resp)
    })
    //...
}

Enter fullscreen mode Exit fullscreen mode

The results are as follows:

{"level":"debug","msg":"message received successfully: my request","span_id":"445ef16484a171b8","time":"2022-07-04T06:27:35+08:00","trace_flags":"01","trace_id":"e9e579b32c9d6b0598f8f33d65689e06"}
Enter fullscreen mode Exit fullscreen mode

Example Code

Summary

The Hertz provides the Opentelemetry extension obs-opentelemetry to facilitate the integration of Metric, Tracing and Logger, in the next article we will use Gorm's Open-Telemetry extension together with Hertz's Open-Telemetry extension to develop A project.

Reference

Top comments (2)

Collapse
 
kinggo profile image
li-jin-ou

I think so too.