Skip to content

add NewJSONHandler - #110

Draft
lmittmann wants to merge 4 commits into
mainfrom
json-handler
Draft

lmittmann wants to merge 4 commits into
mainfrom
json-handler

Conversation

@lmittmann

Copy link
Copy Markdown
Owner

Adds NewJSONHandler(w io.Writer, opts *Options) slog.Handler that writes tinted logs with attributes formatted as pretty JSON.

Following log/slog's design, the existing handler struct now serves both formats via a new json bool field; the text path is unchanged.

Output format

Everything up to the message is rendered exactly like NewTextHandler. The attributes follow as a pretty JSON object with tab indentation, starting on a new line below the message. If a record has no attributes, no JSON object is rendered.

Nov 10 23:00:00.000 INF test
{
	"key": "val",
	"group": {
		"key2": "val2"
	}
}
  • Keys and JSON tokens ({, }, ,) are dimmed; values are plain.
  • tint.Attr/tint.Err colors apply like in the text handler: dimmed colored key, colored value.
  • Attribute values are encoded like slog.JSONHandler (errors as strings, durations as nanoseconds, times as RFC3339Nano, everything else via encoding/json without HTML escaping).
  • WithAttrs attributes are preformatted and cached, tracking open groups like slog.commonHandler; empty groups are elided.

Tests

  • TestJSONHandler runs all handlerTests cases against a new WantJSON expectation.
  • TestSlogParity (unifies the former TestHandler_Consistency) verifies value-encoding parity byte-for-byte against slog.TextHandler and slog.JSONHandler in text/json subtests.

🤖 Generated with Claude Code

lmittmann and others added 4 commits July 12, 2026 19:10
Add NewJSONHandler that writes log records like NewTextHandler up to the
message, followed by the attributes as pretty JSON with tab indentation.
Keys and JSON tokens are dimmed, values are plain, and tint.Attr colors
apply like in the text handler. Attribute values are encoded like
slog.JSONHandler, verified by TestSlogParity against both slog handlers.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
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.

1 participant