traceid

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2025 License: CC-BY-SA-4.0 Imports: 5 Imported by: 0

Documentation

Overview

Package traceid provides trace ID related functionality.

Core components

Design benefits

  • Simple API for generating and managing trace IDs
  • Middleware for HTTP handlers to automatically manage trace IDs
  • Middleware for logging handlers to automatically manage trace IDs
  • Easy integration with existing context and logging systems
  • Minimal dependencies and no external libraries required

Basic usage

Using the middleware for HTTP handlers:

// Create a middleware that adds a trace ID to the request context
// Apply it to your handler
http.Handle("/", traceid.Middleware(yourHandler))

// The trace ID will be available in the request context
// and can be accessed using traceid.FromContext
id, ok := traceid.FromContext(r.Context())
if ok {
	// Use the trace ID
	fmt.Println("Trace ID:", id)
}

Index

Constants

View Source
const LogKey = "trace_id"

LogKey is the key used to store the trace ID in the log record.

Variables

This section is empty.

Functions

func FromContext

func FromContext(ctx context.Context) (string, bool)

FromContext returns the trace ID from the context.Context.

func Middleware

func Middleware(next http.Handler) http.Handler

Middleware adds a new trace ID to http.Request.Context.

func New

func New() string

New returns a naively unique trace ID.

func WithContext

func WithContext(ctx context.Context, id string) context.Context

WithContext returns a new context.Context with the trace ID.

Types

type LogHandler

type LogHandler struct {
	slog.Handler
	LogKey string // LogKey for the trace ID (Default: [LogKey])
}

LogHandler adds trace IDs from context.Context to slog.Record.

func NewLogHandler

func NewLogHandler(next slog.Handler) *LogHandler

NewLogHandler returns a new LogHandler.

func (*LogHandler) Handle

func (h *LogHandler) Handle(ctx context.Context, r slog.Record) error

Handle may add a slog.Attr to a slog.Record.

func (*LogHandler) WithAttrs

func (h *LogHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new LogHandler with the provided attributes.

func (*LogHandler) WithGroup

func (h *LogHandler) WithGroup(name string) slog.Handler

WithGroup returns a new LogHandler with the provided group name.

Jump to

Keyboard shortcuts

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