如何隐藏所有的键时,使用slog在golang?

nvbavucw  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(101)
var programLevel = new(slog.LevelVar)
programLevel.Set(slog.LevelDebug)

h := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel, AddSource: false})
slog.SetDefault(slog.New(h))

slog.Info("Init driver!")

字符串
电流输出:

time=2023-11-04T21:07:42.208+08:00 level=INFO msg="Init driver"


我想要实现的输出:

2023/11/04 21:27:26 INFO Init driver


我需要设置日志级别并且不删除此项目。programLevel.Set(slog.LevelDebug)

avkwfej4

avkwfej41#

NewTextHandlerlogfmt standard中打印日志消息,为此,我定义了一个名为valuelog的自定义slog.Handler
我的valuelog.go

package valuelog

import (
    "context"
    "io"
    "log/slog"
    "strings"
    "sync"
)

type Handler struct {
    h   slog.Handler
    mu  *sync.Mutex
    out io.Writer
}

func NewHandler(o io.Writer, opts *slog.HandlerOptions) *Handler {
    if opts == nil {
        opts = &slog.HandlerOptions{}
    }
    return &Handler{
        out: o,
        h: slog.NewTextHandler(o, &slog.HandlerOptions{
            Level:       opts.Level,
            AddSource:   opts.AddSource,
            ReplaceAttr: nil,
        }),
        mu: &sync.Mutex{},
    }
}

func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool {
    return h.h.Enabled(ctx, level)
}

func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
    return &Handler{h: h.h.WithAttrs(attrs), out: h.out, mu: h.mu}
}

func (h *Handler) WithGroup(name string) slog.Handler {
    return &Handler{h: h.h.WithGroup(name), out: h.out, mu: h.mu}
}

func (h *Handler) Handle(ctx context.Context, r slog. Record) error {
    
    formattedTime := r.Time.Format("2006/01/02 15:04:05")

    //add time and message to values
    strs := []string{formattedTime, r.Message}

    if r.NumAttrs() != 0 {
        r.Attrs(func(a slog.Attr) bool {
            strs = append(strs, a.Value.String())
            return true
        })
    }

    result := strings.Join(strs, " ")
    b := []byte(result)

    h.mu.Lock()
    defer h.mu.Unlock()

    _, err := h.out.Write(b)

    return err

}

字符集
在上面的自定义slog.Handler中,需要实现以下四个函数:EnabledWithAttrsWithGroupHandle
然后从main.go调用此自定义记录器:

func main() {

    var programLevel = new(slog.LevelVar)
    programLevel.Set(slog.LevelDebug)
    logger := slog.New(valuelog.NewHandler(os.Stdout, &slog.HandlerOptions{Level: programLevel, AddSource: false}))
    logger.Info("Init driver!")

}


附加信息您可能会发现有用的,以及编写缓慢处理程序指南

相关问题