examples/with-tracing/main.go

// Command with-tracing demonstrates X-Ray header parsing and span-id
// propagation through lambdalog's context helpers.
//
// See mercemay.top/src/lambdalog/examples/with-tracing/.
package main

import (
	"context"
	"encoding/json"

	awslambda "github.com/aws/aws-lambda-go/lambda"

	adapter "mercemay.top/src/lambdalog/adapters/lambda"
	"mercemay.top/src/lambdalog/context/requestid"
	"mercemay.top/src/lambdalog/context/tracing"
)

type output struct {
	RequestID string `json:"request_id"`
	SpanID    string `json:"span_id,omitempty"`
	Sampled   bool   `json:"sampled"`
}

type logger struct{}

func (logger) Info(string, ...adapter.Field)         {}
func (logger) Error(string, ...adapter.Field)        {}
func (logger) With(...adapter.Field) adapter.Logger  { return logger{} }

func handle(ctx context.Context, _ []byte) ([]byte, error) {
	id, _ := requestid.Extract(ctx)
	xh, _ := tracing.XRayFromContext(ctx)
	tp, ok := tracing.FromXRay(xh)

	out := output{RequestID: id}
	if ok {
		out.SpanID = tp.ParentID
		out.Sampled = tp.Sampled()
	}
	return json.Marshal(out)
}

func main() {
	// The adapter fills ctx with request id and X-Ray header before the
	// handler runs, so the example can use both without any further setup.
	h := adapter.Handler(logger{}, awslambda.HandlerFunc(handle))
	awslambda.Start(h)
}

// Keep an unused import-free static analysis happy when running locally
// without the lambda runtime. The variable is only read by the compiler;
// it is not exported.
var _ = tracing.XRayTraceEnv

// bytesOut lets callers simulate handler output locally.
func bytesOut(id string) []byte {
	b, _ := json.Marshal(output{RequestID: id})
	return b
}