logger/slog: write stacktrace on error if enabled, and always on fatal
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
		| @@ -270,7 +270,7 @@ func (s *slogLogger) printLog(ctx context.Context, lvl logger.Level, msg string, | ||||
| 		} | ||||
| 	} | ||||
|  | ||||
| 	if s.opts.AddStacktrace && lvl == logger.ErrorLevel { | ||||
| 	if (s.opts.AddStacktrace || lvl == logger.FatalLevel) || (s.opts.AddStacktrace && lvl == logger.ErrorLevel) { | ||||
| 		stackInfo := make([]byte, 1024*1024) | ||||
| 		if stackSize := runtime.Stack(stackInfo, false); stackSize > 0 { | ||||
| 			traceLines := reTrace.Split(string(stackInfo[:stackSize]), -1) | ||||
|   | ||||
| @@ -15,6 +15,24 @@ import ( | ||||
| 	"go.unistack.org/micro/v3/metadata" | ||||
| ) | ||||
|  | ||||
| func TestStacktrace(t *testing.T) { | ||||
| 	ctx := context.TODO() | ||||
| 	buf := bytes.NewBuffer(nil) | ||||
| 	l := NewLogger(logger.WithLevel(logger.ErrorLevel), logger.WithOutput(buf), | ||||
| 		WithHandlerFunc(slog.NewTextHandler), | ||||
| 		logger.WithAddStacktrace(true), | ||||
| 	) | ||||
| 	if err := l.Init(logger.WithFields("key1", "val1")); err != nil { | ||||
| 		t.Fatal(err) | ||||
| 	} | ||||
|  | ||||
| 	l.Error(ctx, "msg1", errors.New("err")) | ||||
|  | ||||
| 	if !bytes.Contains(buf.Bytes(), []byte(`slog_test.go:29`)) { | ||||
| 		t.Fatalf("logger error not works, buf contains: %s", buf.Bytes()) | ||||
| 	} | ||||
| } | ||||
|  | ||||
| func TestWithFields(t *testing.T) { | ||||
| 	ctx := context.TODO() | ||||
| 	buf := bytes.NewBuffer(nil) | ||||
|   | ||||
		Reference in New Issue
	
	Block a user