Overview
Automatic instrumentation traces the libraries your application calls. Manual instrumentation traces your own code. Use it to time a checkout step, attach an order ID to a span, or record a failure with the context that explains it.
Prerequisites
- A tracer provider and an exporter must already run in your application. If you use the SDK, finish the core setup in the OpenTelemetry Go instrumentation guide.
- Propagate
context.Contextthrough handlers and business logic. Manual spans derive from these contexts so traces stay connected. - Tested with Go 1.25.1 and OpenTelemetry Go SDK v1.38.0.
Add manual instrumentation
Step 1. Create manual spans
Use the SDK tracer to wrap important work inside custom spans:
import (
"context"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
)
func processOrder(ctx context.Context, orderID string) error {
tracer := otel.Tracer("order-service")
ctx, span := tracer.Start(ctx, "process-order")
defer span.End()
span.SetAttributes(
attribute.String("order.id", orderID),
attribute.String("order.status", "processing"),
)
// Use ctx for downstream work so child spans stay linked.
return nil
}Tips:
- Reuse tracer instances instead of creating a new one for each request.
- Start spans with descriptive names that match business steps (
checkout,fetch-user, etc.). - End every span.
defer span.End()is the safest place for it.
Step 2. Propagate context
Go keeps no ambient trace state. A span finds its parent only through the context.Context you hand it, so Go breaks traces more often than Java or Python. See Context Propagation for the concepts behind this step.
Inside your process
Pass the ctx that tracer.Start returns into every function you want nested under that span:
func processOrder(ctx context.Context, orderID string) error {
ctx, span := tracer.Start(ctx, "process-order")
defer span.End()
// Child of process-order.
validateOrder(ctx, orderID)
// Root span of a brand new trace. The link to process-order is gone.
validateOrder(context.Background(), orderID)
return nil
}A goroutine that outlives the request needs a context you derive on purpose. The request context is canceled once the handler returns, so background work that keeps using it starts from an already-canceled context. context.WithoutCancel keeps the values, including the span, while dropping the cancellation and the deadline:
// Keeps the trace context, drops the request's cancellation. Go 1.21 and later.
bgCtx := context.WithoutCancel(ctx)
go func() {
_, span := tracer.Start(bgCtx, "settle-order")
defer span.End()
// Background work here.
}()Across a service boundary
Instrumentation libraries such as otelhttp inject and extract for you. Write the calls yourself for any hop they do not cover.
Set the span kind on both ends. SigNoz reads Client and Server to build the service map and APM metrics.
On the way out, inject the context into the outgoing headers:
import (
"context"
"io"
"net/http"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/propagation"
"go.opentelemetry.io/otel/trace"
)
func chargeCard(ctx context.Context, body io.Reader) error {
ctx, span := tracer.Start(ctx, "charge-card", trace.WithSpanKind(trace.SpanKindClient))
defer span.End()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://payments.internal/charge", body)
if err != nil {
return err
}
// Writes the traceparent header onto req.
otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Drain the body so the connection can be reused.
_, err = io.Copy(io.Discard, resp.Body)
return err
}On the way in, extract before you start the entry span:
func handleCharge(w http.ResponseWriter, r *http.Request) {
// Returns a context carrying the caller's span, or r.Context() unchanged
// when no traceparent header is present.
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
ctx, span := tracer.Start(ctx, "handle-charge", trace.WithSpanKind(trace.SpanKindServer))
defer span.End()
// handle-charge is now a child of charge-card in the caller's trace.
capturePayment(ctx)
}For a carrier that is not http.Header, such as queue message metadata, use propagation.MapCarrier:
// Publisher
carrier := propagation.MapCarrier{}
otel.GetTextMapPropagator().Inject(ctx, carrier)
msg.Metadata = carrier // map[string]string
// Consumer
ctx := otel.GetTextMapPropagator().Extract(context.Background(), propagation.MapCarrier(msg.Metadata))Step 3. Add attributes and events
Attributes show up as key-value pairs in SigNoz so you can filter and aggregate spans. Events capture notable moments inside a span.
import (
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)
func handlePayment(ctx context.Context, amount float64) {
span := trace.SpanFromContext(ctx)
span.SetAttributes(
attribute.Float64("payment.amount", amount),
attribute.String("payment.currency", "USD"),
attribute.String("payment.method", "credit_card"),
)
span.AddEvent("payment.processed", trace.WithAttributes(
attribute.String("status", "success"),
attribute.String("transaction.id", "txn_123456"),
))
}- Keep attribute keys consistent (use semantic conventions when possible).
- Use events to mark retries, cache hits/misses, queue waits, and similar milestones.
Step 4. Record errors
Flag failures on the span so they are easy to query in SigNoz.
import (
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
func riskyOperation(ctx context.Context) error {
span := trace.SpanFromContext(ctx)
err := doSomethingRisky()
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return err
}
span.SetStatus(codes.Ok, "")
return nil
}RecordErrorattaches stack and message details.- Setting status to
codes.Errorsurfaces the span in SigNoz error views and alerts. - Continue propagating the error upstream so calling code can respond.
Validate
- Trigger the code paths that emit manual spans.
- In SigNoz Traces, filter by
service.nameor your span name. - Open a trace and verify attributes, events, and error status.
- Check the Errors view to confirm failures show up with recorded exceptions.
Troubleshooting
Still not seeing data in SigNoz? Work through Debug missing traces, logs, and metrics, which covers SDK diagnostics, Collector connectivity, and the common ingestion errors for all three signals.
Why don't I see my custom spans in SigNoz?
- Confirm
initTracer(and automatic instrumentation) runs before your application handlers. - Check sampler configuration. Using
TraceIDRatioBased(0.01)in dev may drop most manual spans. - Verify traffic hits the functions where you inserted spans.
Why are child spans missing even though I create them?
- Ensure you pass the
ctxreturned bytracer.Start(ortrace.SpanFromContext) into downstream functions. - HTTP/database client calls must receive the propagated context as well, otherwise traces break across boundaries.
Why does the downstream service start its own trace?
- Make sure that the caller runs
Injecton the outgoing request and that the request carries atraceparentheader. - Make sure that the receiver runs
Extractand passes the returned context intotracer.Start, rather thanr.Context()orcontext.Background(). - Make sure that both services register the same propagator format. See Context Propagation.
Why don't attributes or events appear on the span?
- Attribute keys must be strings and values must use the correct helper (
attribute.String,attribute.Float64, etc.). - Call
span.AddEventorspan.SetAttributesbeforespan.End(). Post-end mutations are ignored. - Avoid reusing finished spans. Always create a new span for each invocation.
Next steps
- Send logs from your Go application using popular logging libraries: Logrus, Zap, or Zerolog
- Correlate traces with logs to accelerate triage across signals
- Add instrumentation to common Go frameworks via the Go instrumentation library catalog
- Read Context Propagation for the wire format and the failure modes shared across languages
Get Help
If you need help with the steps in this topic, please reach out to us on SigNoz Community Slack. If you are a SigNoz Cloud user, please use in product chat support located at the bottom right corner of your SigNoz instance or contact us at cloud-support@signoz.io.