chainguard-dev/clog
GitHub: chainguard-dev/clog
clog 为 Go 1.21+ 标准 slog 提供上下文感知扩展,使日志记录器可以随 context 传递并自动携带上下文字段,全程零外部依赖。
Stars: 32 | Forks: 13
# 👞 clog
[](https://pkg.go.dev/github.com/chainguard-dev/clog)
支持上下文的 [`slog`](https://pkg.go.dev/log/slog)
`slog` 是在 Go 1.21 中引入的,因此使用它需要 Go 1.21 或更高版本。
## 用法
### Context Logger
Context Logger 可用于从 context 中获取并使用 Logger。有时这比 [Context Handler](#context-handler) 更受青睐,因为它可以更轻松地在不同的上下文(例如测试)中使用不同的 logger。
这种方法深受
[`knative.dev/pkg/logging`](https://pkg.go.dev/knative.dev/pkg/logging) 的启发,但它[完全零依赖标准库之外的包](https://github.com/chainguard-dev/clog/blob/main/go.mod)(与 [`pkg/logging` 的依赖](https://pkg.go.dev/knative.dev/pkg/logging?tab=imports) 相比)。
```
package main
import (
"context"
"log/slog"
"github.com/chainguard-dev/clog"
)
func main() {
// One-time setup
log := clog.New(slog.Default().Handler()).With("a", "b")
ctx := clog.WithLogger(context.Background(), log)
f(ctx)
}
func f(ctx context.Context) {
// Grab logger from context and use.
log := clog.FromContext(ctx)
log.Info("in f")
// Add logging context and pass on.
ctx = clog.WithLogger(ctx, log.With("f", "hello"))
g(ctx)
}
func g(ctx context.Context) {
// Grab logger from context and use.
log := clog.FromContext(ctx)
log.Info("in g")
// Package level context loggers are also aware
clog.ErrorContext(ctx, "asdf")
}
```
```
$ go run .
2009/11/10 23:00:00 INFO in f a=b
2009/11/10 23:00:00 INFO in g a=b f=hello
2009/11/10 23:00:00 ERROR asdf a=b f=hello
```
#### 测试
`slogtest` 包提供了一些实用工具,可以轻松创建使用原生测试日志功能的 logger。
```
func TestFoo(t *testing.T) {
ctx := slogtest.TestContextWithLogger(t)
for _, tc := range []string{"a", "b"} {
t.Run(tc, func(t *testing.T) {
clog.FromContext(ctx).Infof("hello world")
})
}
}
```
```
$ go test -v ./examples/logger
=== RUN TestLog
=== RUN TestLog/a
=== NAME TestLog
slogtest.go:20: time=2023-12-12T18:42:53.020-05:00 level=INFO msg="hello world"
=== RUN TestLog/b
=== NAME TestLog
slogtest.go:20: time=2023-12-12T18:42:53.020-05:00 level=INFO msg="hello world"
--- PASS: TestLog (0.00s)
--- PASS: TestLog/a (0.00s)
--- PASS: TestLog/b (0.00s)
PASS
ok github.com/chainguard-dev/clog/examples/logger
```
### Context Handler
Context Handler 可用于从 context 中插入值。
```
func init() {
slog.SetDefault(slog.New(clog.NewHandler(slog.NewTextHandler(os.Stdout, nil))))
}
func main() {
ctx := context.Background()
ctx = clog.WithValues(ctx, "foo", "bar")
// Use slog package directly
slog.InfoContext(ctx, "hello world", slog.Bool("baz", true))
// glog / zap style (note: can't pass additional attributes)
clog.ErrorContextf(ctx, "hello %s", "world")
}
```
```
$ go run .
time=2009-11-10T23:00:00.000Z level=INFO msg="hello world" baz=true foo=bar
time=2009-11-10T23:00:00.000Z level=ERROR msg="hello world" foo=bar
```
标签:EVTX分析, 日志审计