1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-03-31 21:55:32 +02:00
opentelemetry-go/example/dice/rolldice_go1.22.go
Tyler Yahn 56bb4cf63e
Add logs to dice example (#5349)
* Add logs to dice example

Use slog to log a message on the server handler.

* Add changelog entry

* Split impl for 1.22 and 1.21
2024-05-14 13:00:49 -07:00

43 lines
939 B
Go

// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
//go:build go1.22
// +build go1.22
package main
import (
"fmt"
"io"
"math/rand"
"net/http"
"strconv"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
)
func rolldice(w http.ResponseWriter, r *http.Request) {
ctx, span := tracer.Start(r.Context(), "roll")
defer span.End()
roll := 1 + rand.Intn(6)
var msg string
if player := r.PathValue("player"); player != "" {
msg = fmt.Sprintf("%s is rolling the dice", player)
} else {
msg = "Anonymous player is rolling the dice"
}
logger.InfoContext(ctx, msg, "result", roll)
rollValueAttr := attribute.Int("roll.value", roll)
span.SetAttributes(rollValueAttr)
rollCnt.Add(ctx, 1, metric.WithAttributes(rollValueAttr))
resp := strconv.Itoa(roll) + "\n"
if _, err := io.WriteString(w, resp); err != nil {
logger.ErrorContext(ctx, "Write failed", "error", err)
}
}