← 中文资源

简体中文版本

Slog WithGroup 嵌套属性作用域

WithGroup 给之后添加的属性加分组前缀,With 把属性固定到该 logger 的每条记录;ReplaceAttr 还能去掉 time 让输出可复现。

阅读英文原文

实现说明

Slog WithGroup 嵌套属性作用域可以归结为函数 main。

常见问题

「Slog WithGroup 嵌套属性作用域」这个示例怎么运行?

把它当完整程序编译/解释运行即可——不需要先安装任何东西。

核心语句

return slog.Attr{}

代码示例

package main

import (
	"log/slog"
	"os"
)

func main() {
	// drop the time attribute so repeated runs print identical lines
	handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey {
				return slog.Attr{}
			}
			return a
		},
	})
	base := slog.New(handler)

	// With attaches attributes that appear on every record from this logger
	scoped := base.With("request_id", "r-1042")
	scoped.Info("payment accepted", "amount_cents", 4950)

	// WithGroup nests every later attribute under a dotted prefix
	httpLog := scoped.WithGroup("http")
	httpLog.Info("route matched", "method", "GET", "path", "/orders")

	// nested groups compose into deeper dotted paths
	dbLog := httpLog.WithGroup("db")
	dbLog.Warn("slow query", "ms", 412)
}