Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

1.3 KB
Raw Blame
package loghandler

import (
	"context"
	"log/slog"

	"github.com/SigNoz/signoz/pkg/errors"
	"github.com/SigNoz/signoz/pkg/types/instrumentationtypes"
)

type exception struct{}

func NewException() *exception {
	return &exception{}
}

func (h *exception) Wrap(next LogHandler) LogHandler {
	return LogHandlerFunc(func(ctx context.Context, record slog.Record) error {
		var foundErr error
		newRecord := slog.NewRecord(record.Time, record.Level, record.Message, record.PC)
		record.Attrs(func(a slog.Attr) bool {
			if a.Key == "exception" {
				if err, ok := a.Value.Any().(error); ok {
					foundErr = err
					return true
				}
			}
			newRecord.AddAttrs(a)
			return true
		})

		if foundErr == nil {
			return next.Handle(ctx, record)
		}

		t, c, m, _, _, _ := errors.Unwrapb(foundErr)

		newRecord.AddAttrs(
			slog.String(instrumentationtypes.ExceptionType, t.String()),
			slog.String(instrumentationtypes.ExceptionCode, c.String()),
			slog.String(instrumentationtypes.ExceptionMessage, m),
		)

		// Use the stacktrace captured at error creation time if available.
		type stacktracer interface {
			Stacktrace() string
		}
		if st, ok := foundErr.(stacktracer); ok && st.Stacktrace() != "" {
			newRecord.AddAttrs(slog.String(instrumentationtypes.ExceptionStacktrace, st.Stacktrace()))
		}

		return next.Handle(ctx, newRecord)
	})
}