traceid

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2025 License: MIT Imports: 4 Imported by: 7

README

TraceId

Go pkg to propagate TraceId header across multiple services.

  • Enables simple tracing capabilities and log grouping.
  • The value can be exposed to end-users in case of an error.
  • The value is UUIDv7, which lets you infer the timestamp.
  • Unlike OTEL, this package doesn't trace spans or metrics, doesn't require any backend and doesn't have large dependencies (GRPC).

Example - HTTP middleware

package main

import (
	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/go-chi/httplog/v2"
	"github.com/go-chi/traceid"
)

func main() {
	r := chi.NewRouter()

	r.Use(traceid.Middleware)
	r.Use(httplog.RequestLogger(logger()))
	r.Use(middleware.Recoverer)

	r.Use(func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			ctx := r.Context()

			// Log traceId to request logger.
			traceID := traceid.FromContext(r.Context())
			httplog.LogEntrySetField(ctx, "traceId", slog.StringValue(traceID))

			next.ServeHTTP(w, r.WithContext(ctx))
		})
	})

See example/main.go

Example: Send HTTP request with TraceId header

import (
	"github.com/go-chi/traceid"
)

func main() {
	// Set TraceId in context, if not set from parent ctx yet.
	ctx := traceid.NewContext(context.Background())

	// Make a request with TraceId header.
	req, _ := http.NewRequestWithContext(ctx, "GET", "http://localhost:3333/proxy", nil)
	traceid.SetHeader(ctx, req)

	resp, err := http.DefaultClient.Do(req)
	//...
}

Example: Set TraceId header in all outgoing HTTP requests globally

import (
	"github.com/go-chi/traceid"
	"github.com/go-chi/transport"
)

func main() {
	// Send TraceId in all outgoing HTTP requests.
	http.DefaultTransport = transport.Chain(
		http.DefaultTransport,
		transport.SetHeader("User-Agent", "my-app/v1.0.0"),
		traceid.Transport,
	)
	
	// This will automatically send TraceId header.
	req, _ := http.NewRequest("GET", "http://localhost:3333/proxy", nil)
	_, _ = http.DefaultClient.Do(req)
}

Get time from UUIDv7 value

$ go run github.com/go-chi/traceid/cmd/traceid 018e0ee7-3605-7d75-b344-01062c6fd8bc
2024-03-05 14:56:57.477 +0100 CET

You can also create a new UUIDv7:

$ go run github.com/go-chi/traceid/cmd/traceid
018e0ee7-3605-7d75-b344-01062c6fd8bc

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Header = http.CanonicalHeaderKey("TraceId")
View Source
var LogKey string = "traceId"

Functions

func FromContext

func FromContext(ctx context.Context) string

func LogHandler added in v0.3.0

func LogHandler(handler slog.Handler) slog.Handler

You can pass slog.Handler, and all the logs would automatically log the traceId if logging with context is used.

slog.Log()
slog.DebugContext()
slog.InfoContext()
slog.WarnContext()
slog.ErrorContext()

Example:

ctx := traceid.NewContext(context.Background())
handler := traceid.LogHandler(slog.NewJSONHandler(os.Stdout, nil))
logger := slog.New(handler)
logger.InfoContext(ctx, "message")

This would log

{"time":"2025-04-01T13:17:43.097789397Z","level":"INFO","msg":"message","traceId":"0195f180-2939-7bc4-bffe-838eb3c62526"}

func Middleware

func Middleware(next http.Handler) http.Handler

func NewContext

func NewContext(ctx context.Context) context.Context

func SetHeader

func SetHeader(ctx context.Context, req *http.Request)

func Transport added in v0.2.0

func Transport(next http.RoundTripper) http.RoundTripper

Types

type RoundTripFunc added in v0.2.0

type RoundTripFunc func(r *http.Request) (*http.Response, error)

RoundTripFunc, similar to http.HandlerFunc, is an adapter to allow the use of ordinary functions as http.RoundTrippers.

func (RoundTripFunc) RoundTrip added in v0.2.0

func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error)

Directories

Path Synopsis
cmd
traceid command
example module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL