zerolog心得

打印堆栈信息

  1. 必须设置zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
  2. 返回error时必须使用这个包 github.com/pkg/errors
  3. 采用Err方法 zerolog.Error().Err(err)
  4. 使用zerolog.Trace().Stack()
package main

import (
    "bytes"
    "fmt"
    "github.com/pkg/errors"
    "github.com/rs/zerolog"
    "github.com/rs/zerolog/pkgerrors"
)

func main() {
    zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack

    out := &bytes.Buffer{}
    log := zerolog.New(out)

    err := errors.Wrap(errors.New("error message"), "from error")
    log.Trace().Stack().Err(err).Msg("")
    //log.Trace().Stack().Err(err).Send()
    fmt.Println(out.String())
    // {"level":"trace","stack":[{"func":"main","line":"17","source":"main.go"},{"func"
    //:"main","line":"203","source":"proc.go"},{"func":"goexit","line":"1357","source"
    //:"asm_amd64.s"}],"error":"from error: error message"}
}

你可能感兴趣的:(zerolog心得)