Skip to content

fix(json): keep comma after an empty slog group - #232

Open
RaphaelFakhri wants to merge 1 commit into
charmbracelet:mainfrom
RaphaelFakhri:fix/json-empty-group-comma
Open

RaphaelFakhri wants to merge 1 commit into
charmbracelet:mainfrom
RaphaelFakhri:fix/json-empty-group-comma

Conversation

@RaphaelFakhri

Copy link
Copy Markdown
  • I have read CONTRIBUTING.md.
  • I have created a discussion that was approved by a maintainer (for new features).

Bug fix, not a new feature.

Problem

With JSONFormatter, a value that resolves to an empty slog group produces invalid JSON:

type empty struct{}

func (empty) LogValue() slog.Value { return slog.GroupValue() }

l := log.NewWithOptions(os.Stdout, log.Options{Formatter: log.JSONFormatter})
l.Info("message", "lv", empty{}, "k", "v")

Before:

{"level":"info","msg":"message","lv":{}"k":"v"}

After:

{"level":"info","msg":"message","lv":{},"k":"v"}

writeSlogValue calls jw.start() for the nested group, which resets the item counter to 0. An empty group leaves the counter at 0, so the next key is written without a comma.

Change

writeSlogValue saves the counter before writing a group and restores it after. Output for non-empty groups is unchanged.

Tests

TestSlogAttr has a new log valuer empty group case. The case checks both the log and the slog paths. It fails without the change and passes with it. go test ./... and golangci-lint run pass.

Fixes #231

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: JSON formatter writes invalid JSON after an empty slog group

1 participant