logger

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 9 Imported by: 9

Documentation

Overview

Package logger builds the service's *slog.Logger: a JSON handler chain that correlates every record with the active trace, tags it with the service identity, and can fire side-effect hooks per level.

New and NewWithHandler return a plain *slog.Logger, so the same logger is used everywhere — HTTP/gRPC handlers, business code, background workers and SDK packages — and third-party code logs through the same handler.

Usage

Build one logger at startup and inject it:

b := buildinfo.Read()
log := logger.New(os.Stdout, logger.Config{
	Service:   "myapp",   // service.name
	Version:   b.Version, // service.version — the build version
	Level:     logger.LevelInfo,
	AddSource: true,
})
log.InfoContext(ctx, "service started", "addr", ":8080", "build", b)

access := log.With("logger", "access") // child tagged logger=access
access.InfoContext(ctx, "request", "method", "GET", "path", "/")

Always log with a context (InfoContext, ErrorContext, ...; the sloglint linter enforces it): the context carries cancellation and the span the record is correlated with.

Correlation and identity

When the context carries a valid OpenTelemetry span context, every record gets trace_id, span_id and trace_flags at its top level — outside any WithGroup — so a collector can link the line to its trace. Without one the fields are omitted. Config.Service and Config.Version are written as service.name and service.version, the OpenTelemetry resource attribute names; an empty Version is omitted.

Multiple sinks

To split output by level, combine handlers with slog.NewMultiHandler and pass it to NewWithHandler. Each wrapped handler's own Enabled check gates which records it receives:

stdout := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: logger.LevelInfo})
h := slog.NewMultiHandler(stdout, sentryHandler) // sentryHandler.Enabled gates ERROR+
log := logger.NewWithHandler(h, logger.Config{Service: "myapp", Version: b.Version})

Side-effect hooks (Events)

Events attaches a per-level callback that fires IN ADDITION to normal handling — the record is still written to every sink. Use it for side effects like alerting or Sentry capture on ERROR, without disturbing stdout logging:

log := logger.New(os.Stdout, logger.Config{
	Service: "myapp",
	Level:   logger.LevelInfo,
	Events: logger.Events{
		Error: func(ctx context.Context, r slog.Record) {
			alert.Capture(ctx, r) // r carries service.*, trace fields and With attrs
		},
	},
})

The callback receives the full slog.Record with the accumulated With and service.* attributes and the trace fields replayed in, so it sees the same context the sink writes. It runs synchronously before the write, so keep it fast (offload slow work to a goroutine) and do not log at the same level from within it (that re-enters the hook).

Events is a hook, not a router: it is additive to whatever sink you built. To send full records to several destinations by level, use slog.NewMultiHandler (above); the two combine — a multi-handler sink plus an Error hook.

Conventions

  • Errors go under the key "err" with an error value: log.ErrorContext(ctx, "save failed", "err", err).
  • A recovered panic is logged with PanicArgs: err plus exception.stacktrace.
  • Custom levels stay within [-8, 15], the range OpenTelemetry severity numbers map to.

Config

Config fields:

  • Service: written as "service.name" on every record.
  • Version: written as "service.version"; empty omits it.
  • Level: minimum level handled (LevelDebug/LevelInfo/LevelWarn/LevelError).
  • AddSource: attach a "source" attribute shortened to file:line.
  • Events: optional per-level side-effect hook (see above); zero = none.

New applies Level and AddSource to its JSON handler; NewWithHandler leaves both to the handler it is given.

Example

Every record carries the identity of the service and, when the context has a span, the ids of its trace; a child logger adds its own attributes.

package main

import (
	"context"
	"log/slog"
	"os"

	"go.opentelemetry.io/otel/trace"

	"github.com/assanoff/skit/logger"
)

// noTime drops the time of a record, so the output of an example is stable.
func noTime(groups []string, a slog.Attr) slog.Attr {
	if len(groups) == 0 && a.Key == slog.TimeKey {
		return slog.Attr{}
	}
	return a
}

func main() {
	h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: noTime})
	log := logger.NewWithHandler(h, logger.Config{Service: "orders", Version: "v1.2.3"})

	traceID, _ := trace.TraceIDFromHex("4bf92f3577b34da6a3ce929d0e0e4736")
	spanID, _ := trace.SpanIDFromHex("00f067aa0ba902b7")
	ctx := trace.ContextWithSpanContext(context.Background(),
		trace.NewSpanContext(trace.SpanContextConfig{
			TraceID: traceID, SpanID: spanID, TraceFlags: trace.FlagsSampled,
		}))

	log.InfoContext(ctx, "order created", "order_id", 42)
	log.With("logger", "access").InfoContext(context.Background(), "request", "path", "/")
}
Output:
{"level":"INFO","msg":"order created","service.name":"orders","service.version":"v1.2.3","order_id":42,"trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","span_id":"00f067aa0ba902b7","trace_flags":"01"}
{"level":"INFO","msg":"request","service.name":"orders","service.version":"v1.2.3","logger":"access","path":"/"}

Index

Examples

Constants

View Source
const (
	LevelDebug = slog.LevelDebug
	LevelInfo  = slog.LevelInfo
	LevelWarn  = slog.LevelWarn
	LevelError = slog.LevelError
)

Log levels, re-exported from slog for convenience.

Variables

This section is empty.

Functions

func New

func New(w io.Writer, cfg Config) *slog.Logger

New builds a logger writing JSON to w. For several sinks, build the logger with NewWithHandler over slog.NewMultiHandler instead. A logger over io.Discard drops every record before it is built and fires no Events hook.

Example

A service builds one logger at startup, named after its build, and injects it everywhere.

package main

import (
	"context"
	"os"

	"github.com/assanoff/skit/buildinfo"
	"github.com/assanoff/skit/logger"
)

func main() {
	b := buildinfo.Read()
	log := logger.New(os.Stdout, logger.Config{
		Service:   "orders",
		Version:   b.Version,
		Level:     logger.LevelInfo,
		AddSource: true,
	})
	log.InfoContext(context.Background(), "starting service", "build", b)
}

func NewWithHandler

func NewWithHandler(h slog.Handler, cfg Config) *slog.Logger

NewWithHandler builds a logger over a custom slog.Handler (e.g. one made by slog.NewMultiHandler). The service identity and Events from cfg are applied.

Everything is installed at the handler layer, so it applies to every logger derived with With/WithGroup and to third-party code logging through the same handler (e.g. httplog). The handler stack, innermost (closest to the sink) first, is:

h (the given sink)
└─ eventHandler   (if cfg.Events is set: side-effect hooks, additive)
   └─ WithAttrs(service.name, service.version)
      └─ traceHandler (trace_id, span_id, trace_flags; see below)

traceHandler reads the span context from the ctx of each call and, when it is valid, adds trace_id, span_id and trace_flags at the top level of the record, outside any WithGroup. The event hook sits below service and trace so its callback sees the record with the full context it is written with.

func PanicArgs added in v0.14.0

func PanicArgs(p any, args ...any) []any

PanicArgs returns the arguments a recovered panic p is logged with, followed by args: err, the error value "panic: <p>", and exception.stacktrace, the stack of the goroutine that recovered it. Call it in the deferred function:

if p := recover(); p != nil {
	log.ErrorContext(ctx, "panic recovered", logger.PanicArgs(p, "path", r.URL.Path)...)
}
Example

PanicArgs logs a recovered panic under err, with the stack of the goroutine as exception.stacktrace.

package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/assanoff/skit/logger"
)

// noTime drops the time of a record, so the output of an example is stable.
func noTime(groups []string, a slog.Attr) slog.Attr {
	if len(groups) == 0 && a.Key == slog.TimeKey {
		return slog.Attr{}
	}
	return a
}

func main() {
	h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == "exception.stacktrace" {
				a.Value = slog.StringValue("...")
			}
			return noTime(groups, a)
		},
	})
	log := logger.NewWithHandler(h, logger.Config{Service: "orders"})

	func() {
		defer func() {
			if p := recover(); p != nil {
				log.ErrorContext(context.Background(), "panic recovered",
					logger.PanicArgs(p, "path", "/orders")...)
			}
		}()
		panic("nil map")
	}()
}
Output:
{"level":"ERROR","msg":"panic recovered","service.name":"orders","err":"panic: nil map","exception.stacktrace":"...","path":"/orders"}

Types

type Config

type Config struct {
	// Service tags every record with the service name (attribute
	// "service.name").
	Service string
	// Version tags every record with the build version (attribute
	// "service.version"); empty omits it.
	Version string
	// Level is the minimum level handled. New applies it; NewWithHandler
	// leaves level filtering to the given handler.
	Level Level
	// AddSource attaches a "source" attribute (file:line) to records. New
	// applies it; NewWithHandler leaves it to the given handler.
	AddSource bool
	// Events assigns an optional side-effect callback per level (e.g. fire an
	// alert on Error). It is additive: the record is still written to the sink.
	// Zero value installs no hook. See Events.
	Events Events
}

Config configures the logger built by New or NewWithHandler.

type EventFn added in v0.6.0

type EventFn func(ctx context.Context, r slog.Record)

EventFn is a side-effect callback invoked for a record at its level, IN ADDITION to normal handling — the record is still written to the underlying sink. Typical use: capture ERROR records to Sentry or fire an alert, while stdout logging is untouched.

Unlike a lossy decoded snapshot, the callback receives the full slog.Record, reconstructed to include the attributes accumulated via With and the service.* attributes (which live on the handler, not the record) plus trace_id, span_id and trace_flags, so the hook sees the same context the record is written with.

The callback runs synchronously on the logging goroutine, before the write. Keep it fast: offload slow work (network calls) to a goroutine or buffered channel. Do NOT log at the hooked level from inside the callback — that re-enters the hook and recurses.

type Events added in v0.6.0

type Events struct {
	Debug EventFn
	Info  EventFn
	Warn  EventFn
	Error EventFn
}

Events assigns an EventFn per level. The zero value (all nil) installs no hook; pass it in Config.Events. Hooks are additive to the sink, never a replacement for it — for multi-sink routing use slog.NewMultiHandler.

Example

An Events hook runs in addition to the sink, just before the write, such as an alert on every error; the record carries the identity of the service and the attributes. The hook sees only the levels the sink is enabled for.

package main

import (
	"context"
	"errors"
	"fmt"
	"log/slog"
	"os"

	"github.com/assanoff/skit/logger"
)

// noTime drops the time of a record, so the output of an example is stable.
func noTime(groups []string, a slog.Attr) slog.Attr {
	if len(groups) == 0 && a.Key == slog.TimeKey {
		return slog.Attr{}
	}
	return a
}

func main() {
	h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: noTime})
	log := logger.NewWithHandler(h, logger.Config{
		Service: "orders",
		Events: logger.Events{
			Error: func(_ context.Context, r slog.Record) {
				fmt.Print("alert: ", r.Message)
				r.Attrs(func(a slog.Attr) bool {
					fmt.Print(" ", a)
					return true
				})
				fmt.Println()
			},
		},
	})

	ctx := context.Background()
	log.InfoContext(ctx, "order created")
	log.ErrorContext(ctx, "payment failed", "err", errors.New("card declined"))
}
Output:
{"level":"INFO","msg":"order created","service.name":"orders"}
alert: payment failed service.name=orders err=card declined
{"level":"ERROR","msg":"payment failed","service.name":"orders","err":"card declined"}

type Level

type Level = slog.Level

Level mirrors slog.Level for convenience.

Jump to

Keyboard shortcuts

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