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))
// ...
}
The results are as follows:
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()
}
The results are as follows:
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)
})
//...
}
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"}
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 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.
Top comments (1)
I think so too.