Metrics, Logs & Traces
linkly was instrumented from its first commit, so this section doesn't add code; it checks that the three signals are useful and connects them to the platform's monitoring stack. The Observability course teaches each tool; here the questions are practical: does Prometheus see what the dashboards will need? Can I jump from a log line to its trace? Does a request from the Gateway continue the caller's trace?
| Signal | linkly produces | Collected by (cluster) | Course lesson |
|---|---|---|---|
| Metrics | /metrics: http_requests_total, http_request_duration_seconds, linkly_cache_requests_total, linkly_links_created_total, linkly_build_info, plus Go runtime and process metrics |
Prometheus, through the chart's ServiceMonitor | Instrumenting a Go Service |
| Logs | one JSON object per line on stdout, with trace_id on request lines |
Grafana Alloy (or Promtail) → Loki | Structured Logging |
| Traces | one server span per request, W3C traceparent propagation |
OTLP → OpenTelemetry Collector → Tempo or Jaeger | The OpenTelemetry SDK |
All three, in one session
The session runs linkly with OTEL_TRACES_EXPORTER=console (spans as JSON on stderr, into spans.json), starts a real Prometheus that scrapes linkly every second, and sends some traffic: one link, five redirects, one unknown code, and one redirect carrying a traceparent header, as a Gateway or an upstream service would send. A bounded loop waits until Prometheus has scraped all of it. Then it queries Prometheus, and prints the request log lines and a summary of every span:
initdb -D pgdata -U linkly --auth=trust >/dev/null
mkdir -p pgrun
pg_ctl -D pgdata -o "-k /home/learner/pgrun -c listen_addresses=" -l pg.log start >/dev/null
createdb linkly
redis-server --port 6379 --bind 127.0.0.1 --daemonize yes --dir /home/learner
mkdir linkly && cd linkly
cat > main.go <<'EOF'
package main
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/prometheus/client_golang/prometheus"
"github.com/redis/go-redis/v9"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/exporters/stdout/stdouttrace"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/sdk/resource"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
)
// version is stamped at build time: go build -ldflags "-X main.version=1.4.0"
var version = "dev"
type config struct {
Addr, DatabaseURL, RedisAddr, BaseURL, LogLevel, Traces string
CacheTTL, ShutdownGrace time.Duration
}
func env(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
// loadConfig reads the twelve-factor configuration from the environment.
func loadConfig() (config, error) {
c := config{
Addr: env("LISTEN_ADDR", ":8080"),
DatabaseURL: env("DATABASE_URL", ""),
RedisAddr: env("REDIS_ADDR", "localhost:6379"),
BaseURL: env("BASE_URL", "http://localhost:8080"),
LogLevel: env("LOG_LEVEL", "info"),
Traces: env("OTEL_TRACES_EXPORTER", "none"),
}
var err error
if c.CacheTTL, err = time.ParseDuration(env("CACHE_TTL", "1h")); err != nil {
return c, fmt.Errorf("CACHE_TTL: %w", err)
}
if c.ShutdownGrace, err = time.ParseDuration(env("SHUTDOWN_GRACE", "10s")); err != nil {
return c, fmt.Errorf("SHUTDOWN_GRACE: %w", err)
}
if c.DatabaseURL == "" {
return c, errors.New("DATABASE_URL is required")
}
return c, nil
}
func main() {
cfg, err := loadConfig()
var level slog.Level
if err == nil {
err = level.UnmarshalText([]byte(cfg.LogLevel))
}
log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level}))
if err == nil {
err = run(cfg, log)
}
if err != nil {
log.Error("linkly stopped", "err", err)
os.Exit(1)
}
}
func run(cfg config, log *slog.Logger) error {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
shutdownTracing, err := setupTracing(cfg.Traces, os.Stderr)
if err != nil {
return err
}
defer shutdownTracing(context.Background())
db, err := pgxpool.New(ctx, cfg.DatabaseURL)
if err != nil {
return fmt.Errorf("database: %w", err)
}
defer db.Close()
if err := migrate(ctx, db); err != nil {
return fmt.Errorf("migrate: %w", err)
}
redis.SetLogger(redisLogger{log})
rdb := newRedis(cfg.RedisAddr)
defer rdb.Close()
app := newApp(pgStore{db}, rdb, cfg, log, prometheus.DefaultRegisterer, prometheus.DefaultGatherer)
srv := &http.Server{Addr: cfg.Addr, Handler: app.Handler(), ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second}
errc := make(chan error, 1)
go func() {
log.Info("listening", "addr", cfg.Addr, "version", version)
errc <- srv.ListenAndServe()
}()
select {
case err := <-errc:
return err
case <-ctx.Done():
}
log.Info("shutting down", "grace", cfg.ShutdownGrace.String())
app.draining.Store(true) // /readyz now answers 503
sctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownGrace)
defer cancel()
if err := srv.Shutdown(sctx); err != nil {
return err
}
log.Info("stopped")
return nil
}
// newRedis takes host:port or a redis:// or rediss:// (TLS) URL. The short timeouts keep
// the cache from slowing requests down when Redis is unwell.
func newRedis(addr string) *redis.Client {
opt, err := redis.ParseURL(addr)
if err != nil {
opt = &redis.Options{Addr: addr}
}
opt.DialTimeout, opt.DialerRetries, opt.MaxRetries = time.Second, 1, 1
opt.ReadTimeout, opt.WriteTimeout = 300*time.Millisecond, 300*time.Millisecond
return redis.NewClient(opt)
}
// redisLogger sends go-redis's own messages to the JSON log instead of plain stderr.
type redisLogger struct{ log *slog.Logger }
func (r redisLogger) Printf(ctx context.Context, format string, v ...any) {
r.log.WarnContext(ctx, fmt.Sprintf(format, v...), "component", "go-redis")
}
// setupTracing installs the OpenTelemetry SDK; "console" writes spans as JSON to w.
func setupTracing(exporter string, w io.Writer) (func(context.Context) error, error) {
res := resource.NewSchemaless(semconv.ServiceName("linkly"), semconv.ServiceVersion(version))
opts := []sdktrace.TracerProviderOption{sdktrace.WithResource(res)}
switch exporter {
case "none":
case "console":
exp, err := stdouttrace.New(stdouttrace.WithWriter(w))
if err != nil {
return nil, err
}
opts = append(opts, sdktrace.WithSyncer(exp))
default:
return nil, fmt.Errorf("OTEL_TRACES_EXPORTER=%q: this build supports none and console", exporter)
}
tp := sdktrace.NewTracerProvider(opts...)
otel.SetTracerProvider(tp)
otel.SetTextMapPropagator(propagation.TraceContext{})
return tp.Shutdown, nil
}
EOF
cat > app.go <<'EOF'
package main
import (
"context"
"crypto/rand"
"encoding/json"
"errors"
"log/slog"
"net/http"
"net/url"
"regexp"
"runtime"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/redis/go-redis/v9"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel/attribute"
semconv "go.opentelemetry.io/otel/semconv/v1.26.0"
"go.opentelemetry.io/otel/trace"
)
type App struct {
store Store
cache *redis.Client
ttl time.Duration
baseURL string
log *slog.Logger
newCode func() string
draining atomic.Bool
metrics http.Handler
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
cacheReqs *prometheus.CounterVec
created prometheus.Counter
}
func newApp(store Store, cache *redis.Client, cfg config, log *slog.Logger,
reg prometheus.Registerer, g prometheus.Gatherer) *App {
f := promauto.With(reg)
a := &App{store: store, cache: cache, ttl: cfg.CacheTTL, baseURL: cfg.BaseURL, log: log,
newCode: randomCode, metrics: promhttp.HandlerFor(g, promhttp.HandlerOpts{}),
requests: f.NewCounterVec(prometheus.CounterOpts{Name: "http_requests_total",
Help: "HTTP requests by route and status code."}, []string{"route", "code"}),
duration: f.NewHistogramVec(prometheus.HistogramOpts{Name: "http_request_duration_seconds",
Help: "Time to handle a request, by route.",
Buckets: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5}}, []string{"route"}),
cacheReqs: f.NewCounterVec(prometheus.CounterOpts{Name: "linkly_cache_requests_total",
Help: "Redis lookups for redirects, by result (hit, miss, error)."}, []string{"result"}),
created: f.NewCounter(prometheus.CounterOpts{Name: "linkly_links_created_total",
Help: "Short links created."}),
}
f.NewGaugeVec(prometheus.GaugeOpts{Name: "linkly_build_info", Help: "Always 1; labels describe the build."},
[]string{"version", "goversion"}).WithLabelValues(version, runtime.Version()).Set(1)
return a
}
func (a *App) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /links", a.createLink)
mux.HandleFunc("GET /{code}", a.redirect)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { w.Write([]byte("ok\n")) })
mux.HandleFunc("GET /readyz", a.readyz)
mux.Handle("GET /metrics", a.metrics)
notProbe := func(r *http.Request) bool { return !quiet(r.URL.Path) }
return otelhttp.NewHandler(a.observe(mux), "linkly", otelhttp.WithFilter(notProbe))
}
func quiet(route string) bool {
return route == "/healthz" || route == "/readyz" || route == "/metrics"
}
// observe records metrics, names the trace span and logs every request, all by route template.
func (a *App) observe(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rec, r)
route := "unmatched" // r.Pattern is "GET /{code}" once the mux has matched, "" otherwise
if _, p, ok := strings.Cut(r.Pattern, " "); ok {
route = p
}
a.requests.WithLabelValues(route, strconv.Itoa(rec.status)).Inc()
a.duration.WithLabelValues(route).Observe(time.Since(start).Seconds())
span := trace.SpanFromContext(r.Context())
span.SetName(r.Method + " " + route)
span.SetAttributes(semconv.HTTPRoute(route))
level := slog.LevelInfo
if quiet(route) {
level = slog.LevelDebug
} else if rec.status >= 500 {
level = slog.LevelError
}
a.log.LogAttrs(r.Context(), level, "request", slog.String("method", r.Method),
slog.String("route", route), slog.Int("status", rec.status),
slog.String("trace_id", span.SpanContext().TraceID().String()))
})
}
type statusRecorder struct {
http.ResponseWriter
status int
}
func (s *statusRecorder) WriteHeader(code int) { s.status = code; s.ResponseWriter.WriteHeader(code) }
var codeRE = regexp.MustCompile(`^[A-Za-z0-9_-]{3,32}
Metrics, Logs & Traces - DevOps Capstone: Ship a Production Service · ExcelTAD
)
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
// randomCode returns 7 random characters from a 64-letter alphabet (b&63 has no modulo bias).
// They come from crypto/rand, so codes can't be predicted.
func randomCode() string {
b := make([]byte, 7)
if _, err := rand.Read(b); err != nil {
panic(err) // the OS random source failed: nothing sensible is left to do
}
for i := range b {
b[i] = alphabet[b[i]&63]
}
return string(b)
}
func validateURL(raw string) error {
if len(raw) > 2048 {
return errors.New("url is longer than 2048 bytes")
}
u, err := url.Parse(raw)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return errors.New("url must be an absolute http or https URL")
}
return nil
}
func (a *App) createLink(w http.ResponseWriter, r *http.Request) {
var req struct{ URL, Code string }
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": `body must be JSON like {"url": "https://..."}`})
return
}
if err := validateURL(req.URL); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
if req.Code != "" && !codeRE.MatchString(req.Code) {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "code must be 3-32 of A-Z a-z 0-9 _ -"})
return
}
code := req.Code
for attempt := 1; ; attempt++ {
if req.Code == "" {
code = a.newCode()
}
err := a.store.Create(r.Context(), code, req.URL)
if err == nil {
break
}
if errors.Is(err, ErrExists) && req.Code == "" && attempt < 3 {
continue // a random code collided: draw again
}
if errors.Is(err, ErrExists) {
writeJSON(w, http.StatusConflict, map[string]string{"error": "code already taken"})
return
}
a.fail(w, r, err)
return
}
a.created.Inc()
writeJSON(w, http.StatusCreated, map[string]string{"code": code, "short_url": a.baseURL + "/" + code, "url": req.URL})
}
// redirect reads through the cache: Redis first, PostgreSQL on a miss (or when Redis is down).
func (a *App) redirect(w http.ResponseWriter, r *http.Request) {
code, ctx := r.PathValue("code"), r.Context()
if !codeRE.MatchString(code) {
http.NotFound(w, r)
return
}
key := "link:" + code
target, err := a.cache.Get(ctx, key).Result()
result := "hit"
if errors.Is(err, redis.Nil) {
result = "miss"
} else if err != nil {
result = "error"
a.log.WarnContext(ctx, "cache read failed", "err", err)
}
a.cacheReqs.WithLabelValues(result).Inc()
trace.SpanFromContext(ctx).SetAttributes(attribute.String("linkly.cache", result))
if result != "hit" {
if target, err = a.store.Get(ctx, code); errors.Is(err, ErrNotFound) {
http.NotFound(w, r)
return
} else if err != nil {
a.fail(w, r, err)
return
}
if err := a.cache.Set(ctx, key, target, a.ttl).Err(); err != nil {
a.log.WarnContext(ctx, "cache write failed", "err", err)
}
}
http.Redirect(w, r, target, http.StatusFound)
}
// readyz fails only on the database: without Redis, linkly is slower but still correct.
func (a *App) readyz(w http.ResponseWriter, r *http.Request) {
if a.draining.Load() {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"status": "draining"})
return
}
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
defer cancel()
res, code := map[string]string{"status": "ready", "database": "up", "cache": "up"}, http.StatusOK
if err := a.store.Ping(ctx); err != nil {
a.log.WarnContext(ctx, "readiness: database", "err", err)
res["status"], res["database"], code = "unavailable", "down", http.StatusServiceUnavailable
}
if err := a.cache.Ping(ctx).Err(); err != nil {
a.log.WarnContext(ctx, "readiness: cache", "err", err)
res["cache"] = "down"
}
writeJSON(w, code, res)
}
func (a *App) fail(w http.ResponseWriter, r *http.Request, err error) {
a.log.ErrorContext(r.Context(), "request failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
}
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(v)
}
EOF
cat > store.go <<'EOF'
package main
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
var (
ErrNotFound = errors.New("link not found")
ErrExists = errors.New("code already exists")
)
// Store is where links live; pgStore in production, an in-memory fake in unit tests.
type Store interface {
Create(ctx context.Context, code, url string) error
Get(ctx context.Context, code string) (string, error)
Ping(ctx context.Context) error
}
const schema = `CREATE TABLE IF NOT EXISTS links (
code text PRIMARY KEY,
url text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now())`
func migrate(ctx context.Context, db *pgxpool.Pool) error {
_, err := db.Exec(ctx, schema)
return err
}
type pgStore struct{ db *pgxpool.Pool }
func (s pgStore) Create(ctx context.Context, code, url string) error {
_, err := s.db.Exec(ctx, `INSERT INTO links (code, url) VALUES ($1, $2)`, code, url)
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" { // unique_violation
return ErrExists
}
return err
}
func (s pgStore) Get(ctx context.Context, code string) (string, error) {
var url string
err := s.db.QueryRow(ctx, `SELECT url FROM links WHERE code = $1`, code).Scan(&url)
if errors.Is(err, pgx.ErrNoRows) {
return "", ErrNotFound
}
return url, err
}
func (s pgStore) Ping(ctx context.Context) error { return s.db.Ping(ctx) }
EOF
go mod init github.com/acme/linkly >/dev/null 2>&1 && go mod tidy 2>/dev/null
go build -ldflags "-X main.version=1.4.0" -o linkly . && cd ..
export DATABASE_URL="postgres:///linkly?host=/home/learner/pgrun" REDIS_ADDR=127.0.0.1:6379 OTEL_TRACES_EXPORTER=console
./linkly/linkly > linkly.log 2> spans.json &
for i in $(seq 50); do curl -sf localhost:8080/healthz >/dev/null && break; sleep 0.1; done
cat > prometheus.yml <<'X'
global: {scrape_interval: 1s}
scrape_configs:
- job_name: linkly
static_configs: [{targets: ["127.0.0.1:8080"], labels: {env: sandbox}}]
X
prometheus --config.file=prometheus.yml --storage.tsdb.path=./data --web.listen-address=127.0.0.1:9090 >prom.log 2>&1 &
curl -s -o /dev/null -X POST localhost:8080/links -d '{"url": "https://go.dev/doc/", "code": "docs"}'
for i in 1 2 3 4 5; do curl -s -o /dev/null localhost:8080/docs; done
curl -s -o /dev/null localhost:8080/nope
curl -s -o /dev/null -H 'traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' localhost:8080/docs
for i in $(seq 100); do
[ "$(promtool query instant http://127.0.0.1:9090 'sum(linkly_cache_requests_total)' 2>/dev/null | cut -d' ' -f3)" = 7 ] && break; sleep 0.2
done
q() { promtool query instant -o json http://127.0.0.1:9090 "$1" | jq -r '.[] | "\(.metric | del(.__name__) | to_entries | map("\(.key)=\(.value)") | join(",")) => \(.value[1])"'; }
echo "== Prometheus scraped linkly"
q 'up'
q 'sum by (route, code) (http_requests_total{job="linkly", route!="/metrics"})'
q 'sum by (result) (linkly_cache_requests_total)'
q 'http_request_duration_seconds_count{route="/{code}"}'
q 'linkly_build_info'
kill %1 %2; wait
echo "== log lines"
jq -c 'select(.msg == "request") | {route, status, trace_id}' linkly.log
echo "== spans"
jq -c '{name: .Name, trace: .SpanContext.TraceID, parent_remote: .Parent.Remote,
cache: ([.Attributes[] | select(.Key == "linkly.cache") | .Value.Value][0]),
status: ([.Attributes[] | select(.Key == "http.response.status_code") | .Value.Value][0])}' spans.json== Prometheus scraped linkly
env=sandbox,instance=127.0.0.1:8080,job=linkly => 1
code=200,route=/healthz => 1
code=201,route=/links => 1
code=302,route=/{code} => 6
code=404,route=/{code} => 1
result=hit => 5
result=miss => 2
env=sandbox,instance=127.0.0.1:8080,job=linkly,route=/{code} => 7
env=sandbox,goversion=go1.27.3,instance=127.0.0.1:8080,job=linkly,version=1.4.0 => 1
== log lines
{"route":"/links","status":201,"trace_id":"dda74c84d8762e6e024a2a363feda972"}
{"route":"/{code}","status":302,"trace_id":"a68b2e1abaae7c2eab93800a5094b78e"}
{"route":"/{code}","status":302,"trace_id":"8928c1e481d92f84feb9ff1afa36d540"}
{"route":"/{code}","status":302,"trace_id":"68a29faede89671374629b6de882b3d5"}
{"route":"/{code}","status":302,"trace_id":"8f8548c37075779b449e4ec13f6074b2"}
{"route":"/{code}","status":302,"trace_id":"d3b4ceab7a49d4ddde454a347c47ac71"}
{"route":"/{code}","status":404,"trace_id":"3001d33afe7dc81dd33a52ab9d7c52c2"}
{"route":"/{code}","status":302,"trace_id":"4bf92f3577b34da6a3ce929d0e0e4736"}
== spans
{"name":"POST /links","trace":"dda74c84d8762e6e024a2a363feda972","parent_remote":false,"cache":null,"status":201}
{"name":"GET /{code}","trace":"a68b2e1abaae7c2eab93800a5094b78e","parent_remote":false,"cache":"miss","status":302}
{"name":"GET /{code}","trace":"8928c1e481d92f84feb9ff1afa36d540","parent_remote":false,"cache":"hit","status":302}
{"name":"GET /{code}","trace":"68a29faede89671374629b6de882b3d5","parent_remote":false,"cache":"hit","status":302}
{"name":"GET /{code}","trace":"8f8548c37075779b449e4ec13f6074b2","parent_remote":false,"cache":"hit","status":302}
{"name":"GET /{code}","trace":"d3b4ceab7a49d4ddde454a347c47ac71","parent_remote":false,"cache":"hit","status":302}
{"name":"GET /{code}","trace":"3001d33afe7dc81dd33a52ab9d7c52c2","parent_remote":false,"cache":"miss","status":404}
{"name":"GET /{code}","trace":"4bf92f3577b34da6a3ce929d0e0e4736","parent_remote":true,"cache":"hit","status":302}
What to notice
Prometheus adds the target labels. linkly exports http_requests_total{route, code}; Prometheus attached job, instance and the static env label from its scrape configuration. In the cluster, the ServiceMonitor plus the Prometheus Operator produce namespace, pod, service and job labels the same way. That is why the alert rules in the next lesson select {job="linkly"}: they depend on scrape configuration, not on anything in the code.
Six redirects, five hits. The first redirect after creating the link was the miss; the unknown code was a second miss. http_request_duration_seconds_count{route="/{code}"} agrees with the request counter (7 requests to that route), which is a quick sanity check worth doing whenever you add a histogram. The query excludes route="/metrics": Prometheus's own scrapes are counted too, and their number depends on how many scrapes happened, so they don't belong in a deterministic example (or in a traffic dashboard).
linkly_build_info carries version="1.4.0". During a rollout, count by (version) (linkly_build_info) shows how many pods run each version, and joining on it puts the version next to any other metric.
Every request log line has a trace_id, and it matches the span's trace ID one to one. In Grafana, a derived field on the Loki data source turns that field into a link to the trace in Tempo; the reverse direction (trace to logs) uses the same ID. Grep-able correlation for free, because observe logs inside the request's context.
The last span continues a remote trace. Its trace ID is the one from the traceparent header (4bf92f35…) and parent_remote is true: otelhttp extracted the W3C context because setupTracing installed the TraceContext propagator. Without that one line, every service would start a new trace and distributed tracing would stop at the first hop. The span also carries linkly.cache (hit, miss), so a slow trace tells you immediately whether PostgreSQL was involved.
Probes are not traced. otelhttp.WithFilter drops /healthz, /readyz and /metrics; the session's first /healthz call has no span. With a 5-second readiness probe on three pods, unfiltered probes would be most of your tracing bill.
In the cluster
Metrics. The chart's ServiceMonitor (serviceMonitor.enabled: true in both environments) points Prometheus at the http port's /metrics. Check the target in Prometheus's UI under Status → Targets, or with a query:
$ kubectl -n monitoring port-forward svc/monitoring-kube-prometheus-prometheus 9090 &
$ promtool query instant http://localhost:9090 'up{job="linkly", namespace="linkly-production"}'
up{container="linkly", endpoint="http", instance="10.244.1.17:8080", job="linkly", namespace="linkly-production", pod="linkly-7d9f8c6b5-4xk2p", service="linkly"} => 1 @[1767225600]
up{container="linkly", endpoint="http", instance="10.244.2.9:8080", job="linkly", namespace="linkly-production", pod="linkly-7d9f8c6b5-qm7tn", service="linkly"} => 1 @[1767225600]
up{container="linkly", endpoint="http", instance="10.244.3.12:8080", job="linkly", namespace="linkly-production", pod="linkly-7d9f8c6b5-zr8wd", service="linkly"} => 1 @[1767225600]Logs. Nothing to configure in linkly: the container runtime writes stdout to the node, and a log agent (Grafana Alloy as a DaemonSet, installed with the Loki chart) ships it to Loki with Kubernetes labels. Keep labels few (namespace, app, pod) and filter by JSON fields at query time (Loki & LogQL):
{namespace="linkly-production", app="linkly"} | json | level="ERROR"
{namespace="linkly-production", app="linkly"} | json | msg="request" | status >= 500 | line_format "{{.route}} {{.trace_id}}"
sum by (route) (count_over_time({namespace="linkly-production", app="linkly"} | json | msg="request" [5m]))Traces. The sandbox build supports none and console. For the cluster, add the OTLP exporter (module go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc) as a third case in setupTracing, and use a batching span processor instead of the synchronous one:
case "otlp":
// reads OTEL_EXPORTER_OTLP_ENDPOINT, e.g. http://otel-collector.monitoring:4317
exp, err := otlptracegrpc.New(context.Background())
if err != nil {
return nil, err
}
opts = append(opts, sdktrace.WithBatcher(exp), sdktrace.WithSampler(
sdktrace.ParentBased(sdktrace.TraceIDRatioBased(0.1))))Then set OTEL_TRACES_EXPORTER=otlp and OTEL_EXPORTER_OTLP_ENDPOINT in the chart's ConfigMap. ParentBased(TraceIDRatioBased(0.1)) keeps 10% of new traces but always follows the caller's decision, so a trace sampled upstream is never cut in half (Sampling). The Collector, not the app, decides where spans go (Tempo, Jaeger or a vendor), so changing backends never needs a linkly release (The Collector).
Test yourself
Where do the job, instance (and in the cluster namespace, pod) labels on linkly's metrics come from?
- linkly adds them in code
- Prometheus attaches them from the scrape configuration (ServiceMonitor) and service discovery
- Grafana adds them
- The Go runtime
The last span had the trace ID from the traceparent header. What made that work?
- Prometheus
- The TraceContext propagator installed in setupTracing, used by otelhttp to extract the incoming context
- The log handler
- Redis
Why does otelhttp.WithFilter drop /healthz, /readyz and /metrics from tracing?
- They can't be traced
- Probe and scrape traffic is constant and uninteresting, and would dominate trace volume and cost
- OpenTelemetry forbids it
- They have no route