spruce

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2024 License: MIT Imports: 8 Imported by: 1

README

Spruce

Spruce pretty-prints Go structured logs for humans.

Documentation Latest Version Build Status Code Coverage

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.

Example Usage

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>

Documentation

Overview

Package spruce providers an slog.Handler that writes pretty-printed structured logs to a testing.T (or compatible) logger.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewStreamHandler added in v0.2.0

func NewStreamHandler(w io.Writer) slog.Handler

NewStreamHandler returns a new slog.Handler that writes to w.

func NewStreamLogger added in v0.2.0

func NewStreamLogger(w io.Writer) *slog.Logger

NewStreamLogger returns a slog.Logger that writes to w.

func NewTestHandler added in v0.2.0

func NewTestHandler(t TestingT) slog.Handler

NewTestHandler returns a new slog.Handler that writes to t.

func NewTestLogger added in v0.2.0

func NewTestLogger(t TestingT) *slog.Logger

NewTestLogger returns a slog.Logger that writes to t.

Types

type TestingT

type TestingT interface {
	Log(...any)
}

TestingT is the subset of testing.TB that is used to write logs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL