Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Stacktrace for rs/zerolog users

masso
May 10, 2024

Stacktrace for rs/zerolog users

Asakusa.go #2 LT from masso

About:
- How to use stacktrace in rs/zerolog

masso

May 10, 2024
Tweet

More Decks by masso

Other Decks in Technology

Transcript

  1. Index type Index struct { Title string PresentationLength float64 //

    [minutes] } var indexes = []Index{ {"Self Introduction", 0.5}, {"We're using zerolog", 0.5}, {"The mechanism of stacktrace in zerolog", 1}, {"How to customize stacktrace in zerolog", 1.5}, {"Q&A", 1}, } Asakusa.go #2 - Title 2024/05/10 @masso 2
  2. Self Introduction GitHub: @sota0121 I'm working at Money Forward, Inc.

    as a full- stack software engineer. Go, TypeScript, React, Next.js, AWS, k8s, Terraform, etc. Asakusa.go #2 - Title 2024/05/10 @masso 3
  3. We're using zerolog rs/zerolog: Zero Allocation JSON Logger Structured logging

    with simple API that is inspired by go.uber.org/zap Main features are here Asakusa.go #2 - Title 2024/05/10 @masso 4
  4. The mechanism of stacktrace in zerolog - basic usage import

    ( "github.com/rs/zerolog" "github.com/rs/zerolog/pkgerrors" ) zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack func printStackTrace(err error) { // setLogFields ze := log.WithLevel(zerolog.ErrorLevel).Caller(2) // Stacktrace ze.Stack().Err(err).Msg("") } Asakusa.go #2 - Title 2024/05/10 @masso 5
  5. The mechanism of stacktrace in zerolog details main codes rs/zerolog/event.go,

    rs/zerolog/globals.go, rs/zerolog/pkgerrors/stacktrace.go stackTracer interface を満たすものを Unwrap しながら探る // pkgerrors/stacktrace.go import "github.com/pkg/errors" func MarshalStack(err error) interface{} { type stackTracer interface { StackTrace() errors.StackTrace } var sterr stackTracer var ok bool for err != nil { sterr, ok = err.(stackTracer) if ok { break } u, ok := err.(interface { Unwrap() error }) if !ok { return nil } err = u.Unwrap() } if sterr == nil { return nil } Asakusa.go #2 - Title 2024/05/10 @masso 6
  6. How to customize stacktrace in zerolog 自前のスタックトレース処理を利用したい場合は、 zerolog.ErrorStackMarshaler に設定する signature:

    func(err error) interface{} import "github.com/pkg/errors" func CustomFormatStackTrace(err error) string { if err, ok := err.(interface{ StackTrace() errors.StackTrace }); ok { stack := err.StackTrace() formatted := "" for _, frame := range stack { formatted += fmt.Sprintf("%+v\n", frame) } return formatted } return "No stack trace available" } Asakusa.go #2 - Title 2024/05/10 @masso 7