Skip to content

Commit

Permalink
slogutil: jsonl logformat
Browse files Browse the repository at this point in the history
  • Loading branch information
Mizzick committed Oct 18, 2024
1 parent 72234b6 commit b50b124
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions logutil/slogutil/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const (
FormatDefault Format = "default"
FormatJSON Format = "json"
FormatJSONHybrid Format = "jsonhybrid"
FormatJSONL Format = "jsonl"
FormatText Format = "text"
)

Expand All @@ -20,6 +21,7 @@ func NewFormat(s string) (f Format, err error) {
FormatDefault,
FormatJSON,
FormatJSONHybrid,
FormatJSONL,
FormatText:
return f, nil
default:
Expand Down
33 changes: 33 additions & 0 deletions logutil/slogutil/slogutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ func New(c *Config) (l *slog.Logger) {
Level: lvl,
ReplaceAttr: replaceAttr,
})
case FormatJSONL:
h = NewJSONHybridHandler(output, &slog.HandlerOptions{
Level: lvl,
ReplaceAttr: newJSONLReplaceAttr(),
})
case FormatText:
h = slog.NewTextHandler(output, &slog.HandlerOptions{
Level: lvl,
Expand Down Expand Up @@ -134,6 +139,34 @@ func ReplaceLevel(groups []string, a slog.Attr) (res slog.Attr) {
return a
}

// newJSONLReplaceAttr is a function that returns
// [slog.HandlerOptions.ReplaceAttr] function for [FormatJSONHybrid] format.
func newJSONLReplaceAttr() func(groups []string, a slog.Attr) (res slog.Attr) {
return func(groups []string, a slog.Attr) (res slog.Attr) {
return SimplifyLevel(groups, RemoveTime(groups, a))
}
}

// normalAttrValue is a NORMAL value under the [slog.LevelKey] key.
var normalAttrValue = slog.StringValue("NORMAL")

// SimplifyLevel is a function for [slog.HandlerOptions.ReplaceAttr] that
// replaces level attribute values below ERROR with NORMAL.
func SimplifyLevel(groups []string, a slog.Attr) (res slog.Attr) {
if len(groups) > 0 {
return a
}

if a.Key == slog.LevelKey {
lvl := a.Value.Any().(slog.Level)
if lvl < LevelError {
a.Value = normalAttrValue
}
}

return a
}

// RemoveTime is a function for [slog.HandlerOptions.ReplaceAttr] that removes
// the "time" attribute.
func RemoveTime(groups []string, a slog.Attr) (res slog.Attr) {
Expand Down

0 comments on commit b50b124

Please sign in to comment.