Help us shape the future of Go! Take the 2026 Go Developer Survey

logging

package
v1.20.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

Documentation

Overview

Package logging 提供框架的日志机制:slog.Handler 装饰器族与 请求级日志属性的上下文传播(request_id/user_id 等全链路字段)。

Index

Constants

View Source
const (
	// FieldRequestID 是 request_id 日志属性 key。
	FieldRequestID = "request_id"
	// FieldUserID 是 user_id 日志属性 key。
	FieldUserID = "user_id"
)

全链路日志字段的标准 key:HTTP 中间件、pubsub 传播等机制以这些 key 读写日志属性,跨机制保持命名一致。

Variables

This section is empty.

Functions

func AttrsFrom

func AttrsFrom(ctx context.Context) []slog.Attr

AttrsFrom 返回 ctx 中存储的请求级日志属性,未设置时返回 nil。

func NewAttrsHandler

func NewAttrsHandler(h slog.Handler) slog.Handler

NewAttrsHandler 返回包装 h 的 slog.Handler:log 调用的 Context 携带 请求级属性(WithAttrs 写入)时,自动为记录追加这些属性。 与 NewTraceHandler 组合使用:NewAttrsHandler(NewTraceHandler(base))。

func NewTraceHandler

func NewTraceHandler(h slog.Handler) slog.Handler

NewTraceHandler 返回包装 h 的 slog.Handler:log 调用的 Context 携带 有效的 OpenTelemetry SpanContext 时,自动追加 trace_id 与 span_id。 同时包装纯 slog handler 与 zap 桥接的 slog handler(contrib/zap)。

已知取舍(AUX-10):经 WithGroup 后注入的 trace_id/span_id 会被嵌套 进 group(slog 装饰器在组内追加属性是标准行为),Loki/ELK 等按顶层 字段提取的采集端将拿不到。需要在顶层提取 trace 关联时,建议不要对 日志 handler 使用 WithGroup,或在采集侧以顶层字段另行注入。

func WithAttrs

func WithAttrs(ctx context.Context, attrs ...slog.Attr) context.Context

WithAttrs 将请求级日志属性写入 ctx,供 NewAttrsHandler 注入到该 上下文范围内的每条日志记录。同 key 的属性以最新写入为准(覆盖旧值): 跨调用时新批次覆盖旧值;同一批次内重复 key 时取最后一次传入的值 (等价于逐个 WithAttrs 的叠加语义),其余重复项丢弃。 写入空 attrs 时原样返回 ctx。

Types

This section is empty.

Jump to

Keyboard shortcuts

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