Documentation
¶
Overview ¶
Package traceid provides trace ID related functionality.
Core components ¶
- New: Generates a new trace ID
- WithContext: Adds a trace ID to a context.Context
- FromContext: Retrieves a trace ID from a context.Context
- Middleware: Middleware for HTTP handlers to manage trace IDs
- LogHandler: Middleware for logging handlers to manage trace IDs
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 ¶
FromContext returns the trace ID from the context.Context.
func Middleware ¶
Middleware adds a new trace ID to http.Request.Context.
func WithContext ¶
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 ¶
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.
Click to show internal directories.
Click to hide internal directories.