skip to content
Alvin Lucillo

Simple tracing in Go

/ 2 min read

💻 Tech

Tracing is a powerful observability tool to understand more about a system, especially distributed systems. This is helpful in many things like debugging and performance monitoring. The example code below demonstrates a simple trace with OpenTelemetry in Go. The output shows the start and end time of the span, events, and attributes. With data like the sample output, you can use it with tools like ELK stack, Jaeger, Elastic APM, and AWS X-Ray to visualize and analyze the data.

func main() {
	ctx := context.Background()

	// Stdout exporter that prints to console
	exporter, err := stdouttrace.New(stdouttrace.WithPrettyPrint())
	if err != nil {
		log.Fatalf("Failed to create an exporter: %v", err)
	}

	// Simple span processor
	spanProcessor := trace.NewSimpleSpanProcessor(exporter)

	// Tracer provider with the simple span processor
	tp := trace.NewTracerProvider(
		trace.WithSpanProcessor(spanProcessor),
		trace.WithResource(resource.NewWithAttributes(
			semconv.SchemaURL,
			semconv.ServiceNameKey.String("SampleService"),
		)),
	)
	defer func() {
		if err := tp.Shutdown(ctx); err != nil {
			log.Fatalf("Failed to shut down tracer provider: %v", err)
		}
	}()

	// Tracer provider as the global provider
	otel.SetTracerProvider(tp)

	// Get a tracer
	tracer := otel.Tracer("sample-tracer")

	// Start a new span
	_, span := tracer.Start(ctx, "sample-span")
	log.Println("Sample log")

	span.AddEvent("Sample event")
	span.SetAttributes(attribute.KeyValue{Key: "user.id", Value: attribute.StringValue("12345")})

	// End the span
	span.End()
}

Sample output after running go run main.go:

2024/05/10 19:12:01 Sample log
{
        "Name": "sample-span",
        "SpanContext": {
                "TraceID": "8b0a15935aeb9645ea25d84c38895f48",
                "SpanID": "9ae8ec6e761a2575",
                "TraceFlags": "01",
                "TraceState": "",
                "Remote": false
        },
        "Parent": {
                "TraceID": "00000000000000000000000000000000",
                "SpanID": "0000000000000000",
                "TraceFlags": "00",
                "TraceState": "",
                "Remote": false
        },
        "SpanKind": 1,
        "StartTime": "2024-05-10T19:12:01.103389979+08:00",
        "EndTime": "2024-05-10T19:12:01.103429453+08:00",
        "Attributes": [
                {
                        "Key": "user.id",
                        "Value": {
                                "Type": "STRING",
                                "Value": "12345"
                        }
                }
        ],
        "Events": [
                {
                        "Name": "Sample event",
                        "Attributes": null,
                        "DroppedAttributeCount": 0,
                        "Time": "2024-05-10T19:12:01.103428558+08:00"
                }
        ],
        "Links": null,
        "Status": {
                "Code": "Unset",
                "Description": ""
        },
        "DroppedAttributes": 0,
        "DroppedEvents": 0,
        "DroppedLinks": 0,
        "ChildSpanCount": 0,
        "Resource": [
                {
                        "Key": "service.name",
                        "Value": {
                                "Type": "STRING",
                                "Value": "SampleService"
                        }
                }
        ],
        "InstrumentationLibrary": {
                "Name": "sample-tracer",
                "Version": "",
                "SchemaURL": ""
        }
}