サンプル
github.com/lmittmann/tint v1.2.0: Intercept, rewrite, and suppress source locations, built-in attributes, and hierarchical group fields using tint.Options.ReplaceAttr
検証済みサンプル — golang github.com/lmittmann/tint v1.2.0: Intercept, rewrite, and suppress source locations, built-in attributes, and hierarchical group fields…
sha256:6fdf0275f43c82295f836ff4ca53426ed7d8b2baf0b87ccdbdfc86ae8eaae5c5
このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。
合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。
MIT-0
実行証拠
宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。
- 証拠の基準
- 署名済みコントラクト合格
- 検証レシート
- 3
- ビルドした署名鍵
- 3
宣言された環境
go linux x64 go go go
検証実行環境
| 環境 | コントラクト | ステージ | 実行日 |
|---|---|---|---|
| go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-17 |
| go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1 |
2026-08-18 |
| go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f… |
2026-09-07 |
ケース
HOW- ゴール
- Intercept, rewrite, and suppress source locations, built-in attributes, and hierarchical group fields using tint.Options.ReplaceAttr
- シンボル
-
- tint.NewTextHandler
- tint.Options
- tint.Attr
- 環境
- go
- 作成日
- 2026-08-17T19:21:08Z
コントラクト
- tint.NewTextHandler formats source code locations directly between the level badge and log message as a faint prefix instead of a trailing key-value pair, and allows complete suppression or replacement via ReplaceAttr
- ReplaceAttr receives *slog.Source for slog.SourceKey and returning an empty slog.Attr removes the source prefix completely without leftover spacing
- ReplaceAttr intercepts built-in slog keys including slog.LevelKey, slog.MessageKey, and slog.TimeKey for custom level tagging, payload rewriting, or timestamp omission
- Nested WithGroup handlers and inline slog.Group attributes pass their full group hierarchy to ReplaceAttr while tint formats keys with dot notation and prunes empty groups entirely
- ReplaceAttr can dynamically return tint.Attr or tint.Err to conditionally colorize attributes based on runtime values
ファイル
- NOTES.md
- csx.json
- go.mod
- go.sum
- tint_test.go
ソース
# Notes on github.com/lmittmann/tint
## Prior Solutions Found
A search returned existing sample `sha256:88e08d7f7ab9442485d2696bb1794adefcc732abb423dcf105e9231ca9c30a4f`, which covered basic ANSI level colors (INF, WRN, ERR), `tint.Attr` color palette ranges (4, 12, 196), `tint.Err` helper formatting, standard handler fallback unwrapping, `NoColor`, and custom `TimeFormat`.
This sample investigates a different set of behaviors: the execution model of `tint.Options.ReplaceAttr`, source code location prefix positioning versus standard slog handlers, built-in key interception (`slog.LevelKey`, `slog.MessageKey`, `slog.TimeKey`, `slog.SourceKey`), hierarchical group stack propagation with dot prefixing, and empty group pruning.
## Pinned Release
- `github.com/lmittmann/tint` at `v1.2.0` (pinned in `go.mod` and `go.sum`).
## Observed Behaviour
1. **Source Code Location Placement & Styling**:
- In standard Go `slog.TextHandler`, enabling `AddSource: true` emits the caller location as a trailing key-value attribute (`source=file.go:line` or `source.file=...`).
- In `tint.NewTextHandler`, the source location is positioned directly between the level badge and the log message as `<LEVEL> <source> <msg>`.
- In default colorized mode, the source location is wrapped in faint ANSI escape sequences (`\x1b[2m<source>\x1b[0m`).
- With `NoColor: true`, it is printed unstyled as `<LEVEL> <source> <msg>`.
2. **Source Interception and Omission via `ReplaceAttr`**:
- When `AddSource: true` is set, `ReplaceAttr` receives an attribute with `a.Key == slog.SourceKey` whose value is of concrete type `*slog.Source`.
- Returning an empty `slog.Attr{}` suppresses the source location prefix completely without leaving orphan spaces or delimiters.
- Returning a modified string attribute (e.g. `slog.String(slog.SourceKey, "server.go:42")`) replaces the source prefix in-place.
3. **Built-in Key Interception (`LevelKey`, `MessageKey`, `TimeKey`)**:
- `ReplaceAttr` is invoked for built-in keys with an empty groups slice (`groups == []string{}`).
- Returning `slog.Attr{}` for `slog.TimeKey` omits the timestamp prefix entirely.
- Returning a modified string for `slog.LevelKey` replaces the 3-letter level tag with the custom string.
- Returning a modified string for `slog.MessageKey` rewrites the message payload.
- Returning `slog.Attr{}` for any record attribute drops the attribute from the log output.
4. **Hierarchical Group Propagation & Empty Group Pruning**:
- Nested groups created via `handler.WithGroup("...")` and record-level inline `slog.Group("...", ...)` pass the full accumulated slice of group names (e.g. `[]string{"service", "v1", "params"}`) to `ReplaceAttr` alongside the attribute's raw key.
- Formatted output keys are prefixed with dot-separated group names (e.g. `service.v1.params.page=1`).
- Empty groups or groups where all inner attributes are dropped by `ReplaceAttr` are completely omitted from the formatted output line.
5. **Dynamic Styling from `ReplaceAttr`**:
- `ReplaceAttr` can return `tint.Attr(colorCode, attr)` or `tint.Err(err)` to dynamically apply ANSI colors or error formatting at record processing time based on attribute keys or values (such as highlighting HTTP 5xx status codes in red).
## How Wrong Expectations Fail
- Models expecting `AddSource` to format as a standard key-value attribute at the end of the line (e.g. `INF msg source=file.go:line`) fail because `tint` outputs the source between the level and message (`INF file.go:line msg`).
- Models expecting `ReplaceAttr` to only receive user-defined record attributes fail because `tint` also dispatches built-in keys (`level`, `msg`, `time`, `source`) through `ReplaceAttr`.
{"case":{"believed":"tint formats AddSource as a standard key-value attribute at the end of the log line matching slog.TextHandler conventions.","caseId":"case:sha256:831faf696f1c630d2181fdc45b43403a60788c1de9aecbfa973eef0cafbd20e9","contract":["tint.NewTextHandler formats source code locations directly between the level badge and log message as a faint prefix instead of a trailing key-value pair, and allows complete suppression or replacement via ReplaceAttr","ReplaceAttr receives *slog.Source for slog.SourceKey and returning an empty slog.Attr removes the source prefix completely without leftover spacing","ReplaceAttr intercepts built-in slog keys including slog.LevelKey, slog.MessageKey, and slog.TimeKey for custom level tagging, payload rewriting, or timestamp omission","Nested WithGroup handlers and inline slog.Group attributes pass their full group hierarchy to ReplaceAttr while tint formats keys with dot notation and prunes empty groups entirely","ReplaceAttr can dynamically return tint.Attr or tint.Err to conditionally colorize attributes based on runtime values"],"goal":"Intercept, rewrite, and suppress source locations, built-in attributes, and hierarchical group fields using tint.Options.ReplaceAttr","kind":"HOW","packages":["pkg:golang/github.com/lmittmann/tint@1.2.0"],"schemaVersion":1,"symbols":["tint.NewTextHandler","tint.Options","tint.Attr"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/lmittmann/tint@1.2.0"],"schemaVersion":1,"symbols":["tint.NewTextHandler","tint.Options","tint.Attr"],"verifierAdapter":"golang@1"}
module codesamplex.dev/sample/tint
go 1.26.5
require github.com/lmittmann/tint v1.2.0
github.com/lmittmann/tint v1.2.0 h1:AogHRHy8HUJUnNJBHJlYa+fR4YY8mko2cnCp67xn9JY=
github.com/lmittmann/tint v1.2.0/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
package tint_test
import (
"bytes"
"context"
"errors"
"log/slog"
"path/filepath"
"runtime"
"testing"
"time"
"github.com/lmittmann/tint"
)
func TestSourcePlacementAndReplacement(t *testing.T) {
var pcs [1]uintptr
runtime.Callers(1, pcs[:])
pc := pcs[0]
// 1. Default colored source placement (between level and message, wrapped in faint escape)
var bufColor bytes.Buffer
hColor := tint.NewTextHandler(&bufColor, &tint.Options{
AddSource: true,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.SourceKey {
if src, ok := a.Value.Any().(*slog.Source); ok && src != nil {
return slog.String(slog.SourceKey, filepath.Base(src.File)+":100")
}
}
return a
},
})
r1 := slog.NewRecord(time.Time{}, slog.LevelInfo, "startup complete", pc)
if err := hColor.Handle(context.Background(), r1); err != nil {
t.Fatalf("unexpected error: %v", err)
}
wantColor := "\x1b[92mINF\x1b[0m \x1b[2mtint_test.go:100\x1b[0m startup complete\n"
if got := bufColor.String(); got != wantColor {
t.Errorf("colored source: got %q, want %q", got, wantColor)
}
// 2. NoColor source placement
var bufPlain bytes.Buffer
hPlain := tint.NewTextHandler(&bufPlain, &tint.Options{
NoColor: true,
AddSource: true,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.SourceKey {
return slog.String(slog.SourceKey, "server.go:42")
}
return a
},
})
r2 := slog.NewRecord(time.Time{}, slog.LevelWarn, "high load", pc)
if err := hPlain.Handle(context.Background(), r2); err != nil {
t.Fatalf("unexpected error: %v", err)
}
wantPlain := "WRN server.go:42 high load\n"
if got := bufPlain.String(); got != wantPlain {
t.Errorf("plain source: got %q, want %q", got, wantPlain)
}
// 3. Suppressed source via empty Attr
var bufDropped bytes.Buffer
hDropped := tint.NewTextHandler(&bufDropped, &tint.Options{
NoColor: true,
AddSource: true,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.SourceKey {
return slog.Attr{}
}
return a
},
})
r3 := slog.NewRecord(time.Time{}, slog.LevelError, "fatal issue", pc)
if err := hDropped.Handle(context.Background(), r3); err != nil {
t.Fatalf("unexpected error: %v", err)
}
wantDropped := "ERR fatal issue\n"
if got := bufDropped.String(); got != wantDropped {
t.Errorf("dropped source: got %q, want %q", got, wantDropped)
}
}
func TestReplaceAttrBuiltinKeys(t *testing.T) {
var buf bytes.Buffer
h := tint.NewTextHandler(&buf, &tint.Options{
NoColor: true,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
switch a.Key {
case slog.TimeKey:
return slog.Attr{} // omit timestamp
case slog.LevelKey:
return slog.String(slog.LevelKey, "CUSTOM_NOTICE")
case slog.MessageKey:
return slog.String(slog.MessageKey, "rewritten payload")
case "drop_me":
return slog.Attr{} // drop attribute
default:
return a
}
},
})
fixedTime := time.Date(2026, 8, 18, 10, 0, 0, 0, time.UTC)
r := slog.NewRecord(fixedTime, slog.LevelInfo, "original message", 0)
r.Add(
slog.String("keep", "ok"),
slog.String("drop_me", "ignored"),
)
if err := h.Handle(context.Background(), r); err != nil {
t.Fatalf("unexpected error: %v", err)
}
want := "CUSTOM_NOTICE rewritten payload keep=ok\n"
if got := buf.String(); got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestGroupHierarchyAndEmptyPruning(t *testing.T) {
type groupCall struct {
groupStack string
key string
}
var calls []groupCall
var buf bytes.Buffer
h := tint.NewTextHandler(&buf, &tint.Options{
NoColor: true,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
stack := ""
for i, g := range groups {
if i > 0 {
stack += "."
}
stack += g
}
calls = append(calls, groupCall{groupStack: stack, key: a.Key})
if a.Key == "secret" || a.Key == "token" {
return slog.Attr{}
}
return a
},
}).WithGroup("service").WithGroup("v1")
r := slog.NewRecord(time.Time{}, slog.LevelInfo, "api dispatch", 0)
r.Add(
slog.String("route", "/users"),
slog.String("token", "redacted_token"),
slog.Group("params",
slog.Int("page", 1),
slog.String("secret", "hidden"),
),
slog.Group("empty_after_drop",
slog.String("secret", "masked"),
),
slog.Group("purely_empty"),
)
if err := h.Handle(context.Background(), r); err != nil {
t.Fatalf("unexpected error: %v", err)
}
want := "INF api dispatch service.v1.route=/users service.v1.params.page=1\n"
if got := buf.String(); got != want {
t.Errorf("got %q, want %q", got, want)
}
// Verify group hierarchy passed into ReplaceAttr for built-in and user attributes
expectedCalls := []groupCall{
{groupStack: "", key: slog.LevelKey},
{groupStack: "", key: slog.MessageKey},
{groupStack: "service.v1", key: "route"},
{groupStack: "service.v1", key: "token"},
{groupStack: "service.v1.params", key: "page"},
{groupStack: "service.v1.params", key: "secret"},
{groupStack: "service.v1.empty_after_drop", key: "secret"},
}
if len(calls) != len(expectedCalls) {
t.Fatalf("expected %d ReplaceAttr calls, got %d: %+v", len(expectedCalls), len(calls), calls)
}
for i, exp := range expectedCalls {
if calls[i] != exp {
t.Errorf("call[%d]: got %+v, want %+v", i, calls[i], exp)
}
}
}
func TestDynamicColoringInReplaceAttr(t *testing.T) {
var buf bytes.Buffer
h := tint.NewTextHandler(&buf, &tint.Options{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == "status" && a.Value.Int64() >= 500 {
return tint.Attr(196, a) // ANSI 196 (red)
}
if a.Key == "err" {
return tint.Err(errors.New(a.Value.String()))
}
return a
},
})
r := slog.NewRecord(time.Time{}, slog.LevelWarn, "upstream error", 0)
r.Add(
slog.Int("status", 502),
slog.String("err", "bad gateway"),
)
if err := h.Handle(context.Background(), r); err != nil {
t.Fatalf("unexpected error: %v", err)
}
want := "\x1b[93mWRN\x1b[0m upstream error \x1b[2;38;5;196mstatus=\x1b[22m502\x1b[0m \x1b[2;91merr=\x1b[22m\"bad gateway\"\x1b[0m\n"
if got := buf.String(); got != want {
t.Errorf("got %q, want %q", got, want)
}
}