golang의zap의hook에 대해서 얘기를 나눠보도록 하겠습니다.
                                            
 3297 단어  golang
                    
순서
본고는 주로 고랑의zap의hook를 연구하고자 합니다.
인스턴스
func hookDemo() {
    count := &atomic.Int64{}
    logger, _ := zap.NewProduction(zap.Hooks(func(entry zapcore.Entry) error {
        fmt.Println("count:", count.Inc(), "msg:", entry.Message)
        return nil
    }))
    defer logger.Sync() // flushes buffer, if any
    sugar := logger.Sugar()
    sugar.Infow("failed to fetch URL",
        // Structured context as loosely typed key-value pairs.
        "url", "https://golang.org",
        "attempt", 3,
        "backoff", time.Second,
    )
    sugar.Info("hello world")
}출력
{"level":"info","ts":1608045721.769727,"caller":"zap/zap_demo.go:29","msg":"failed to fetch URL","url":"https://golang.org","attempt":3,"backoff":1}
count: 1 msg: failed to fetch URL
{"level":"info","ts":1608045721.769826,"caller":"zap/zap_demo.go:35","msg":"hello world"}
count: 2 msg: hello worldHooks
[email protected]/options.go
func Hooks(hooks ...func(zapcore.Entry) error) Option {
    return optionFunc(func(log *Logger) {
        log.core = zapcore.RegisterHooks(log.core, hooks...)
    })
}Hooks 방법은 로그의 코어를zapcore로 사용합니다.Register Hooks가 포장을 했어요.
zapcore.RegisterHooks
[email protected]/zapcore/hook.go
func RegisterHooks(core Core, hooks ...func(Entry) error) Core {
    funcs := append([]func(Entry) error{}, hooks...)
    return &hooked{
        Core:  core,
        funcs: funcs,
    }
}Register Hooks 방법으로 hooked를 만들고, hooks가 hooked의funcs 속성에 값을 부여합니다.
hook
[email protected]/zapcore/hook.go
type hooked struct {
    Core
    funcs []func(Entry) error
}
func (h *hooked) Check(ent Entry, ce *CheckedEntry) *CheckedEntry {
    // Let the wrapped Core decide whether to log this message or not. This
    // also gives the downstream a chance to register itself directly with the
    // CheckedEntry.
    if downstream := h.Core.Check(ent, ce); downstream != nil {
        return downstream.AddCore(ent, h)
    }
    return ce
}
func (h *hooked) With(fields []Field) Core {
    return &hooked{
        Core:  h.Core.With(fields),
        funcs: h.funcs,
    }
}
func (h *hooked) Write(ent Entry, _ []Field) error {
    // Since our downstream had a chance to register itself directly with the
    // CheckedMessage, we don't need to call it here.
    var err error
    for i := range h.funcs {
        err = multierr.Append(err, h.funcs[i](ent))
    }
    return err
}hooked에는 Check, With, Write 방법을 덮어씁니다.확인 방법은hooked를downstream에 추가합니다.Write 메서드는 hooks를 반복해서 리셋합니다.
작은 매듭
Hooks 방법은 로그의 코어를zapcore로 사용합니다.Register Hooks 포장하기;Register Hooks 방법은hooked를 만들고hooks는hooked의funcs 속성에 값을 부여합니다.hooked는 코어를 포장했기 때문에 체크할 때 자신을 등록하고 Write할 때 자신이 등록한 hooks를 실행할 수 있습니다.일반적으로 metrics 등 간단한 조작을hook를 통해 실현할 수 있지만, 복잡한 논리는zapcore를 실현하는 것이 가장 좋다.코어가 해.
doc
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
set containerThere is no built-in set container in Go How to implement Set struct{} => type struct{}{} => 0bytes How to create set :=...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.