Skip to content

Commit

Permalink
feat: proper panic msgs with attrs
Browse files Browse the repository at this point in the history
  • Loading branch information
dd84ai committed Feb 14, 2024
1 parent ffbaec8 commit ff50cb6
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
13 changes: 13 additions & 0 deletions examples/params_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package examples

import (
"errors"
"fmt"
"testing"
"time"

Expand Down Expand Up @@ -67,3 +69,14 @@ func TestCopyingLoggers(t *testing.T) {
logger2.Info("logger2 printed")
logger3.Info("logger3 printed")
}

func TestPanic(t *testing.T) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered. Error:\n", r)
}
}()

logger := typelog.NewLogger("test", typelog.WithLogLevel(typelog.LEVEL_DEBUG), typelog.WithJsonFormat(true))
logger.CheckPanic(errors.New("my custom error"), "i panicked", typelog.Any("smth", 123))
}
8 changes: 6 additions & 2 deletions typelog/msgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,11 @@ func (l *Logger) CheckPanic(err error, msg string, opts ...LogType) {
return
}
args := append([]SlogAttr{}, newSlogArgs(opts...)...)
args = append(args, slog.String("error", fmt.Sprintf("%v", err)))
args = append(args,
slog.String("err_msg", fmt.Sprintf("%v", err)),
slog.String("err_type", fmt.Sprintf("%T", err)),
)
l.logger.Error(msg, args...)
panic(fmt.Sprintf("msg=%s, err=%s errT=%T", msg, err.Error(), err))
panic_logger.Error(msg, args...)
panic(panic_str.String())
}
20 changes: 20 additions & 0 deletions typelog/panic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package typelog

import (
"bytes"
"log/slog"
)

/*
Global logger for writing formatted msg into string we could input to panic.
The point of this code that we get string with all formatted slog.Attrs for panic.
*/

var (
panic_logger *slog.Logger
panic_str *bytes.Buffer = bytes.NewBuffer([]byte{})
)

func init() {
panic_logger = slog.New(slog.NewTextHandler(panic_str, &slog.HandlerOptions{Level: slog.LevelDebug}))
}

0 comments on commit ff50cb6

Please sign in to comment.