Spruce provides an slog.Handler implementation that acts as an adaptor
between an slog.Logger and the io.Writer and testing.TB interfaces.
It is intended for use in places where structured log messages will be read by humans, such as within tests or during development. The output format is not particular suitable for machine parsing; use the built-in JSON or text formatters for that.
package pkg_test
import (
"log/slog"
"testing"
"github.com/dogmatiq/spruce"
)
func TestSomething(t *testing.T) {
// Create a new spruce logger that directs logs to t.
logger := spruce.NewTestLogger(t)
// Run the application code that is being tested, and direct its log output
// to the test log.
systemUnderTest(logger)
}
// systemUnderTest is your existing application code that uses an [slog.Logger].
func systemUnderTest(logger *slog.Logger) {
// Log a message with some complex structured attributes.
logger.Info(
"hello, world!",
slog.Group(
"<group b>",
"<key-1>", "<value-1>",
"<key-2>", "<value-2>",
),
slog.Group(
"<group a>",
"<key-1>", "<value-1>",
),
)
}The above test produces the following output:
spruce.go:76: [INFO] hello, world!
βββ¬ <group b>
β βββ <key-1> β <value-1>
β β°ββ <key-2> β <value-2>
β°ββ¬ <group a>
β°ββ <key-1> β <value-1>