Skip to content

feat(os/glog): add a slog handler forwarding to glog - #4986

Merged
lingcoder merged 7 commits into
gogf:masterfrom
LanceAdd:feat/glog-slog-handler
Nov 19, 2026
Merged

lingcoder merged 7 commits into
gogf:masterfrom
LanceAdd:feat/glog-slog-handler

Conversation

@LanceAdd

@LanceAdd LanceAdd commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

背景

标准库 log/slog 已成为结构化日志的统一入口,glog 还没有接入方式。新增一个把 slog 记录转发到 glog 的 slog.Handler,方便已有 slog 用法的项目继续输出到 glog,且不改变现有日志路径。

改动

新增 glog.NewSlogHandler(logger ...*Logger),返回 *glog.SlogHandler;不传 logger 时使用默认 logger。

  • level 映射:Debug → LEVEL_DEBU;Info → LEVEL_INFO;Info 与 Warn 之间的自定义级别 → LEVEL_NOTI;Warn..Error 之前 → LEVEL_WARN;Error 及以上 → LEVEL_ERRO。
  • attributes:作为键值对透传到 glog 的 Values,等价于直接调用 logger.Info(ctx, msg, k, v, ...);slog.Group 与 WithGroup 展开为 group.key;LogValuer 先 Resolve,空 Attr 跳过。默认文本 handler 按 glog 原生方式空格拼接,HandlerStructure/HandlerJson 按结构化字段输出(需要时自动加引号)。
  • caller:使用 record.PC 推导调用点,-trimpath 构建下同样正确;Error 级别的栈也从 record.PC 起算,并沿用 logger 的栈过滤配置。
  • Enabled:按目标 logger 的级别配置返回,SetLevel 后 slog 侧即可跳过被过滤的级别。
  • WithAttrs、WithGroup 返回新的 handler,不修改原对象,可安全并发使用。

示例:

logger := slog.New(glog.NewSlogHandler(glog.DefaultLogger()))
logger.InfoContext(ctx, "request done",
    slog.String("path", "/api"),
    slog.Group("user", slog.Int("id", 100)),
)

// 默认文本输出,与直接传值一致:
// [INFO] request done path /api user.id 100
// 配合 glog.HandlerStructure:
// Content="request done" path=/api user.id=100

兼容性

  • 不改变现有日志行为;不使用 adapter 时 glog 行为零变化。
  • 不改 Logger 现有方法和公开 API。print 内部拆出 printWithCaller 用于注入 caller PC,GetStack 的过滤器构造提取为 stackFilters(),均行为不变。

测试

  • go test ./os/glog/ -count=1 全包通过;Test_SlogHandler 在 -race 与 -trimpath 下通过。
  • 覆盖:各 level 逐条映射断言(含自定义级别)、属性/分组、LogValuer、空 Attr、结构化输出与引号、caller 与 Error 栈、WithAttrs 切片隔离、并发使用。
  • 变异检验:交换 level 映射、去掉 Resolve、去掉空 Attr 跳过、去掉 slices.Clone、忽略 record.PC 都会使测试失败。

改动文件

os/glog/glog_slog.go             新增:SlogHandler,level/属性/caller/栈映射
os/glog/glog_z_unit_slog_test.go 新增:上述用例
os/glog/glog_logger.go           内部:print 拆出 printWithCaller;GetStack 过滤器抽取 stackFilters()

提交

cb01af79c feat(os/glog): add a slog handler forwarding to glog
1288f6f25 refactor(os/glog): pass slog attrs and caller info to the logger
155cd5e41 test(os/glog): cover empty Attr through record attributes

Add NewSlogHandler, a slog.Handler that forwards records to a glog
logger. Levels map to Debug/Info/Notice/Warning/Error, attributes are
appended to the message as key=value pairs with group prefixes, and
Enabled follows the logger level configuration.

Existing logging behavior is untouched when the handler is not used.
@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.90826% with 11 lines in your changes missing coverage. Please review.
✅ Project coverage is 85.04%. Comparing base (7268e65) to head (9e2c7b7).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
os/glog/glog_slog.go 89.10% 11 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4986      +/-   ##
==========================================
+ Coverage   84.98%   85.04%   +0.05%     
==========================================
  Files         892      893       +1     
  Lines       47047    47151     +104     
==========================================
+ Hits        39984    40098     +114     
+ Misses       7063     7053      -10     
Flag Coverage Δ
go-1.27-core 72.80% <89.90%> (+0.08%) ⬆️
go-1.27-drivers-1 27.58% <2.75%> (-0.07%) ⬇️
go-1.27-drivers-2 27.33% <2.75%> (-0.07%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lingcoder

Copy link
Copy Markdown
Contributor

Thanks for the PR. I ran it in an external module (gf resolved under a github.com/gogf/gf/ path, like a real user) and found two things that don't match the description.

1. Caller info is wrong in -trimpath builds.
With F_FILE_SHORT|F_CALLER_FN, built with -trimpath and no GOROOT env:

direct glog:  [example.com/user.TestProbeDirect] common_test.go:17: direct caller
via slog:     [log/slog.(*Logger).log] logger.go:264: via slog caller

The auto stack on Error also gets two extra frames, log/slog.(*Logger).log and log/slog.(*Logger).Error. Normal builds are fine, because GOROOT frames are filtered there. With -trimpath, runtime.GOROOT() is empty, so the slog frames are not filtered. record.PC is not used.

2. Attributes are flattened into the message text.

slog.Info("q", "k", "a b=c", "nl", "x\n2026-01-01 [ERRO] forged")
// glog output:
//   [INFO] q k=a b=c nl=x
//   2026-01-01 [ERRO] forged

Values are not quoted, so a value with a newline produces a fake log line. With glog.HandlerStructure, everything ends up in one field:

via slog:     Content="msg k=a b user.id=1"
direct glog:  Content=msg k="a b" user.id=1

3. Tests don't catch several changes.
These mutations all still pass Test_SlogHandler_*: swapping the DEBU/INFO mapping, removing Value.Resolve(), removing the empty-Attr skip, removing slices.Clone in WithAttrs. LogValuer support and "safe for concurrent use" are claimed in the description but not tested.

Forward record attributes as key-value pairs so glog handlers format them
like direct logging calls, and use the slog record PC for caller and error
stack information.
@LanceAdd

Copy link
Copy Markdown
Member Author

Thanks for the review. All three points are addressed in the latest push.

1. Caller info with -trimpath

Handle now uses record.PC for the header caller and as the anchor of the Error stack, instead of walking the stack from glog: runtime.CallersFrames([]uintptr{record.PC}).Next() returns the user frame directly (same approach as zapslog and slog-common), so no log/slog frames leak in when runtime.GOROOT() is empty. The anchored stack still applies the logger's filters (StFilter, GOROOT, brief-mode GoFrame filter), which are now shared with GetStack() through stackFilters().

2. Attributes

Attributes are no longer flattened into the message. They are forwarded as key-value pairs in glog's Values, i.e. the equivalent of logger.Info(ctx, msg, "k", v, ...):

  • HandlerStructure: Content=msg k="a b" user.id=1 — values are quoted by glog and newlines are flattened, so no forged lines.
  • Groups expand to group.key (same as zerolog's official SlogHandler); LogValuer is resolved; empty attrs are skipped.

To be explicit about the default text handler: glog natively joins values with spaces and does not quote them (q k a b=c nl x), which is exactly what a direct glog call with values produces. slog-style k="v" text rendering would require changing glog's default value formatting, which I intentionally left out of this PR; happy to follow up separately if you prefer.

3. Tests

Added tests that fail on the mutations you listed:

  • per-message level assertions (catches DEBU/INFO swap);
  • LogValuer (catches missing Resolve);
  • empty Attr passed through record attributes (catches missing empty-attr skip);
  • WithAttrs immutability using a chain with spare slice capacity (catches missing slices.Clone);
  • caller and Error stack assertions that fail under -trimpath when record.PC is ignored;
  • structure output/quoting and concurrent use.

Local runs: go test ./os/glog/ -count=1, -run Test_SlogHandler -trimpath, -run Test_SlogHandler -race, plus go vet and gofmt.

@lingcoder

Copy link
Copy Markdown
Contributor

@LanceAdd thanks, I re-ran the same probes against 53ff806 and all three points check out.

  • Caller: -trimpath builds now report [TestProbe3CallerTrim] slog3_test.go:19 instead of [log/slog.(*Logger).log] logger.go:264, and the Error stack starts at the user frame.
  • Attributes: HandlerStructure gives Content=msg k="a b" user.id=1 nl="x\ny", byte-identical to a direct glog call with values. Default text output matches direct value logging too.
  • Tests: the four mutations (DEBU/INFO swap, dropped Resolve, dropped slices.Clone, callerInfo ignoring record.PC) now all fail on your tests.
  • Direct-call path: I diffed direct glog output (caller, stack, structure handler, values) between master and this branch — identical, and BenchmarkDirectInfo shows the same 632 B/op, 10 allocs/op.

Two edge cases I hit that are not blockers:

1. slog.Any with a struct loses the original type.

slog.Any("struct", P{X: 1, Y: "s"})
via handler:  Content=m struct="{1 s}"
direct glog:  Content=m struct="{\"X\":1,\"Y\":\"s\"}"

attr.Value.String() converts the value before handing it to glog, so under HandlerStructure/HandlerJson a struct field becomes a Go-formatted string instead of a JSON object. Scalars (int, float, bool, time, duration) match exactly.

2. Error stack is empty when Handle runs on another goroutine.
slogStackFromPC looks for record.PC in the current goroutine's frames. If a wrapper handler dispatches Handle asynchronously, slices.Index returns -1 and the stack is silently omitted (3/3 runs). Direct glog is unaffected.

@gqcn

gqcn commented Nov 19, 2026

Copy link
Copy Markdown
Member

这次提交的 log/slog 适配方向合理,结合主分支现有能力和当前实现来看适合合入主库:

  • 对照的现有能力:对照了主分支 os/glog 现有的 Logger.Debug/Info/Notice/Warning/Error/Print、Logger.Write、Logger.GetLevel、Logger.Skip/Stack/SetHandlers,以及 debug/gdebug 的 CallerWithFilter/StackWithFilters。
  • 现有 API 无法覆盖的行为:Logger 现有的公开日志方法和 Write 都只能从 glog 内部回溯当前调用栈,无法直接传入 slog.Record.PC;在 -trimpath 构建且缺少 GOROOT 时,gdebug 的路径过滤和固定 Skip 无法可靠剥离不同调用深度的 log/slog 标准库栈帧,会导致调用点与错误堆栈错位;同时 StStatus、StFilter 及框架栈过滤条件属于包内未导出或内部能力,外部很难在不改动既有 Handlers 或多走一次栈回溯的前提下实现等价的调用点与 Error 堆栈锚定。
  • 新增维护面与收益相称:该实现仅依赖 Go 标准库 log/slog(无新增外部依赖),公开接口只增加了 glog.SlogHandler 与 glog.NewSlogHandler,属性透传和格式化复用现有的 Values、HandlerStructure 等链路,对原有直接调用 glog 的路径也没有引入额外性能开销,新增维护成本与实际收益相称。

当前提交的各项 CI 检查均已通过,此前评审中提出的问题也已在当前代码中确认解决,整体符合合入要求。

@gqcn gqcn added the bot-approved Approved by gf-pr-review label Nov 19, 2026

@lingcoder lingcoder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@lingcoder
lingcoder merged commit 540a21d into gogf:master Nov 19, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-approved Approved by gf-pr-review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants