Skip to content

Commit

Permalink
feat: 添加 WithStd
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Nov 13, 2023
1 parent 8928bea commit c9b8b44
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 7 deletions.
19 changes: 19 additions & 0 deletions log.go
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: MIT

//go:build !go1.21

package logs

import (
"log"

"github.com/issue9/logs/v7/writers"
)

// TODO(go1.21): go1.21 之后可删除,slog 默认会接管 log
func withStd(l *Logs) {
log.SetOutput(writers.WriteFunc(func(b []byte) (int, error) {
l.INFO().String(string(b)) // 参考 slog 默认输出至 INFO
return len(b), nil
}))
}
10 changes: 9 additions & 1 deletion options.go
Expand Up @@ -21,7 +21,15 @@ const (

type Option func(*Logs)

// WithLevels 指定启用的日志通道
// WithStd 是否接管默认的日志处理程序
//
// 如果是 go1.21 之前的版本,会调用 [log.SetOutput] 管理默认日志的输出,输出到 [logs.INFO];
// 如果是 go1.21 之后的版本,会调用 [slog.SetDefault] 管理默认日志的输出;
func WithStd() Option { return func(l *Logs) { withStd(l) } }

// WithLevels 指定启用的日志级别
//
// 之后也可以通过 [Logs.Enable] 进行修改。
func WithLevels(lv ...Level) Option { return func(l *Logs) { l.levels = lv } }

// WithLocale 指定本地化信息
Expand Down
5 changes: 2 additions & 3 deletions slog.go
Expand Up @@ -24,14 +24,13 @@ type slogHandler struct {
prefix string // groups 组成
}

func withStd(l *Logs) { slog.SetDefault(slog.New(l.SLogHandler())) }

// SLogHandler 将 logs 转换为 [slog.Handler] 接口
//
// 所有的 group 会作为普通 attr 的名称前缀,但是不影响 Level、Message 等字段。
func (l *Logs) SLogHandler() slog.Handler { return &slogHandler{l: l} }

// SLog 将 Logs 作为 [slog.Logger] 的后端
func (l *Logs) SLog() *slog.Logger { return slog.New(l.SLogHandler()) }

func (h *slogHandler) Enabled(ctx context.Context, lv slog.Level) bool {
return h.l.IsEnable(slog2Logs[lv])
}
Expand Down
5 changes: 2 additions & 3 deletions slog_test.go
Expand Up @@ -12,12 +12,11 @@ import (
"github.com/issue9/assert/v3"
)

func TestLogs_SLog(t *testing.T) {
func TestLogs_WithStd(t *testing.T) {
a := assert.New(t, false)

buf := new(bytes.Buffer)
l := New(NewTextHandler(buf), WithLocation(true), WithCreated(MilliLayout))
slog.SetDefault(l.SLog())
New(NewTextHandler(buf), WithLocation(true), WithCreated(MilliLayout), WithStd())

slog.Error("error", "a1", "v1")
a.Contains(buf.String(), "error").Contains(buf.String(), "a1=v1")
Expand Down

0 comments on commit c9b8b44

Please sign in to comment.