Created
December 11, 2024 12:37
-
-
Save fanyang89/4b7d5232f8f5f5ae4dd0a98b246b3998 to your computer and use it in GitHub Desktop.
Golang log/slog print cockroachdb errors stacktrace
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type LogHandler struct { | |
writer *bufio.Writer | |
minLevel slog.Level | |
attrs []slog.Attr | |
group string | |
} | |
func NewLogHandler(writer io.Writer, minLevel slog.Level) *LogHandler { | |
return &LogHandler{ | |
writer: bufio.NewWriter(writer), | |
minLevel: minLevel, | |
attrs: make([]slog.Attr, 0), | |
group: "", | |
} | |
} | |
func (m *LogHandler) Enabled(ctx context.Context, level slog.Level) bool { | |
_ = ctx | |
return m.minLevel <= level | |
} | |
func (m *LogHandler) Handle(ctx context.Context, record slog.Record) error { | |
_ = ctx | |
var err error | |
_, err = m.writer.WriteString(record.Time.Format("[2006-01-02 15:04:05] ")) | |
if err != nil { | |
return errors.Wrap(err, "write") | |
} | |
_, err = m.writer.WriteString(fmt.Sprintf("[%s] ", record.Level)) | |
if err != nil { | |
return errors.Wrap(err, "write") | |
} | |
_, err = m.writer.WriteString(record.Message) | |
if err != nil { | |
return errors.Wrap(err, "write") | |
} | |
_, err = m.writer.WriteRune(' ') | |
if err != nil { | |
return errors.Wrap(err, "write") | |
} | |
record.Attrs(func(attr slog.Attr) bool { | |
_, err = m.writer.WriteString(fmt.Sprintf("%s=%+v ", attr.Key, attr.Value.Any())) | |
if err != nil { | |
err = errors.Wrap(err, "iterate attrs") | |
return false | |
} | |
return true | |
}) | |
if err != nil { | |
return err | |
} | |
return m.writer.Flush() | |
} | |
func (m *LogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { | |
return &LogHandler{ | |
writer: m.writer, | |
minLevel: m.minLevel, | |
attrs: append(m.attrs, attrs...), | |
} | |
} | |
func (m *LogHandler) WithGroup(name string) slog.Handler { | |
return &LogHandler{ | |
writer: m.writer, | |
minLevel: m.minLevel, | |
attrs: m.attrs, | |
group: name, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment