Skip to content

proposal: log/slog: Allow control over the order of attributes in the slog (prioritizing the specified key e.g. trace id) #73054

@wangzhione

Description

@wangzhione

Proposal Details

const XRquestID = "X-Request-Id"

var xRquestID = any(XRquestID)

func GetTraceID(c context.Context) string {
	traceID, _ := c.Value(xRquestID).(string)
	return traceID
}

type TraceHandler struct {
	slog.Handler
}

func (h TraceHandler) Handle(ctx context.Context, r slog.Record) error {
	r.AddAttrs(slog.String(XRquestID, GetTraceID(ctx)))
	return h.Handler.Handle(ctx, r)
}

In slog.Handler, dynamically added fields like trace_id always appear at the end of the log line.
This becomes a problem when logs are long — some platforms truncate long lines, causing trace_id to be silently dropped.

Suggestion: Allow control, Trace ID in Before the slog.MessageKey or other control program operations

Metadata

Metadata

Assignees

No one assigned

    Labels

    LibraryProposalIssues describing a requested change to the Go standard library or x/ libraries, but not to a toolProposal

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions