Hertz how to use Opentelemetry for beginners
Tags: go, tutorial, webdev, beginners
Published: 2022-11-28 13:12:33

## Introduction

In the previous [article](https://dev.to/kinggo/http-request-id-association-with-logs-46jc) we focused on the use of [hlog](https://github.com/cloudwego/hertz/tree/develop/pkg/common/hlog) in conjunction with [requestid](https://github.com/hertz-contrib/requestid) to associate logs.
[Hertz](https://github.com/cloudwego/hertz) now also provides extended support for Opentelemetry [obs-opentelemetry](https://github.com/hertz-contrib/obs-opentelemetry) to facilitate the use of Opentelemetry in the [Hertz](https://github.com/cloudwego/hertz) service.

## How to use

The Opentelemetry extension to [Hertz](https://github.com/cloudwego/hertz) provides three main functions: Metric, Tracing and Logging.

### Metric

Use Opentelemetry's Metric at [Hertz](https://github.com/cloudwego/hertz).

It supports HTTP Metrics and Runtime Metrics, more details can be found [here](https://github.com/hertz-contrib/obs-opentelemetry#supported-metrics).

```go
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))
	// ...
}

```

The results are as follows:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1klx0wu6gmz8hb5t4r03.png)





### Tracing

[Hertz](https://github.com/cloudwego/hertz) integrates with Opentelemetry's tracing.

```go
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()
}

```

The results are as follows:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nd5gmdsus6uzyqodpd12.png)




### Logger

[Hertz](https://github.com/cloudwego/hertz) provides logger for association with tracing.

```go
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)
	})
	//...
}

```

The results are as follows:

```bash
{"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"}
```


### Example Code

- Example: https://github.com/cloudwego/hertz-examples/tree/main/opentelemetry
- Documentation: https://www.cloudwego.io/docs/hertz/tutorials/service-governance/Opentelemetry/


## Summary

The [Hertz](https://github.com/cloudwego/hertz) provides the Opentelemetry extension [obs-opentelemetry](https://github.com/hertz-contrib/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

- https://github.com/cloudwego/hertz
- https://github.com/hertz-contrib/obs-opentelemetry