Files
weichenandCursor 2c5716fdcf
ci / vet-and-test (push) Successful in 3s
ci / docker-checkout-hostgateway (push) Successful in 4s
Document the deps submodule path and record the adoption checks.
The trace example still uses its own module replace and continues to pass.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 14:30:57 +00:00

3.8 KiB
Raw Permalink Blame History

Logging-System

跨系统共用的结构化日志库,以及可独立部署的采集服务。目标是把一次请求的运行日志和错误码对齐到同一个 trace_id 上,方便事后追溯。

本仓库是该模块的源码位置。Go 模块路径为 logging-system。只依赖标准库,不依赖错误码模块:只要错误实现了 ErrorCode() 和 ErrorFields(),错误日志会自动带上码和字段。

分层

包 职责 依赖边界
logsys 级别、条目、Logger、上下文追踪、全局默认日志器 只依赖标准库
sink console / 滚动文件 / 异步队列 / HTTP 批量 / 多路分发 只依赖 logsys
redact 写前脱敏(JWT、sk-key、Bearer、api_key、password,可追加正则) 只依赖标准库
config 默认值 ← JSON ← LOGSYS_* 环境变量 组装 logsys 与 sink
slogadapter 与 log/slog 双向转发 只依赖 logsys
server 采集服务,默认 :8092 组合根之一
cli logctl 组合根之一
conformance 并发不丢、异步排空、脱敏、多路一致 只用公开 API

同步与异步

每个出口自己保证并发安全。

模式 行为
同步 调用方 goroutine 在互斥锁内写完(console、file,或 async: false 的 HTTP)
异步 有界队列加单写者。队列满时丢弃最新一条并计数,不阻塞业务 goroutine。Sync / Close 排空队列,关闭有超时

HTTP 出口默认异步攒批(条数或时间间隔)。文件可按大小滚动并保留 N 份历史。

模块级别可以比全局更细,例如全局 info、engine 为 debug、server 为 warn。出口还可以再设自己的最低级别。

配置

完整示例见 docs/example.json。

环境变量覆盖文件:LOGSYS_CONFIG、LOGSYS_LEVEL、LOGSYS_SERVICE、LOGSYS_REDACT(on/off)。

cfg, err := config.Load("log.json")
log, err := config.Build(cfg)
defer log.Close()
log.Module("engine").WithContext(ctx).Error("provider down", err, "step", id)

log.Error 的 err 若带有错误码,条目里会出现 code 和该错误的字段。追踪标识用 logsys.WithTrace 放进 context,或由调用方写入 X-Trace-Id。

采集 API

方法/路径 说明
GET /v1/health 健康检查
POST /v1/logs 正文 {"entries":[...]}。配置了 token 时要求 Authorization: Bearer 或 X-Log-Token
GET /v1/logs trace_id、level(精确)、service、q、cursor、limit
GET /v1/logs/tail SSE。cursor 之后先回放再实时推送;慢消费者丢帧

写入时再脱敏一次,避免客户端绕过进程内红线。

CLI

go build -o bin/logctl .
./bin/logctl serve --addr :8092 --data logs/collector.jsonl --token dev
./bin/logctl query --addr http://127.0.0.1:8092 --trace trace-abc-1 --token dev
./bin/logctl tail --addr http://127.0.0.1:8092 --token dev

开发

go vet ./...
go test -count=1 ./...

依赖本仓库

消费方把本库固定为 submodule,推荐路径 deps/logging-system。版本以消费方 gitlink 为准,不执行 submodule update --remote。

require logging-system v0.0.0

replace logging-system => ./deps/logging-system

并列检出、还没放进 deps/ 时,也可以暂时写 replace logging-system => ../Logging-System。本库不导入错误码模块。若消费方同时依赖 Agent-Native,而 Agent-Native 的 deps/ 里还有一份本库,编译时只认消费方自己的 replace;两份 gitlink 必须相同。

远程:ssh://git@git-ssh.u1680832.nyat.app:31411/weichen/Logging-System.git

与错误码系统的追溯闭环见 docs/integration.md。可运行示例:go test ./examples/trace(两个仓库需为同级目录)。