logging

package
v0.14.1 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package logging provides slog-based logger construction and a network-address redaction helper for Giant Swarm MCP servers.

New picks a structured handler — text for local dev, JSON when running inside a Kubernetes pod (auto-detected via KUBERNETES_SERVICE_HOST).

Init extends New with an OpenTelemetry logs branch: when any of OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, OTEL_EXPORTER_OTLP_ENDPOINT, or OTEL_LOGS_EXPORTER is set, the returned handler is an otelslog.Handler wired to a LoggerProvider that ships records via OTLP. Records emitted from within an active span carry the SpanContext (TraceID + SpanID) for log ↔ trace correlation in Grafana. The Shutdown returned by Init drains the provider on graceful exit; in non-OTLP mode it is a no-op closure.

WithExtraHandlers attaches additional slog.Handler sinks alongside the env-selected primary. Every record reaches the primary and each extra, in either OTLP or non-OTLP mode — the pattern for "OTLP for Loki plus stderr for kubectl logs" is one JSON-on-os.Stderr handler passed through WithExtraHandlers.

Trace correlation differs between the primary and extras: the OTel logs SDK attaches SpanContext to its native LogRecord struct as first-class fields, so the otelslog-based primary picks up TraceID/SpanID without any extra wiring. Stdlib slog handlers (JSONHandler, TextHandler) only render the record's attributes — they ignore the context's SpanContext. WithTraceContextAttrs wraps a handler so the emitted records carry trace_id / span_id keys; use it on extras that need correlation:

stderr := logging.WithTraceContextAttrs(slog.NewJSONHandler(os.Stderr, nil))
logging.Init(ctx, logging.WithExtraHandlers(stderr))

RedactHost scrubs IP addresses and URL userinfo before they land in logs. It is the only redaction primitive in this package because URL parsing plus IPv6 surgery is genuinely non-trivial; format-only redactions (e.g. hashing emails, masking tokens) are short enough that each server can implement its own opinion at the call site or in a custom slog.HandlerOptions.ReplaceAttr.

The slog standard library already provides the LogValuer interface for type-driven redaction — see https://github.com/golang/go/blob/master/src/log/slog/example_logvaluer_secret_test.go — and external libraries such as github.com/m-mizutani/masq cover recursive struct walking. The toolkit deliberately does not pre-bake either pattern.

Deprecated: Use github.com/giantswarm/mcp-toolkit/telemetry/logging.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func RedactHost

func RedactHost(s string) string

RedactHost returns s with IPv4/IPv6 addresses replaced by a redaction marker and userinfo stripped from URLs. Plain hostnames, ports, and paths are preserved.

Accepts either a full URL ("https://192.168.1.10:6443/path") or a bare host ("192.168.1.10:6443", "api.example.com"). RedactHost("") returns "".

Use this when logging an error from an upstream API client whose message may include the API server address — e.g. a Kubernetes API error that interpolates the API server URL.

func WithTraceContextAttrs added in v0.2.0

func WithTraceContextAttrs(h slog.Handler) slog.Handler

WithTraceContextAttrs wraps h so every Handle call receives the active span's TraceID and SpanID as slog.Attrs on the record.

The OTel logs SDK attaches SpanContext to its native LogRecord struct as first-class fields, so otelslog.Handler-based pipelines carry trace correlation without any extra wiring. Stdlib slog.Handler implementations (JSONHandler, TextHandler, and most third-party handlers) only render the record's attributes — they ignore the context's SpanContext. WithTraceContextAttrs bridges that gap: pass a JSON-on-stderr or file handler through it and the emitted records carry trace_id / span_id keys the same way the OTLP path carries them as native fields.

Records emitted outside an active SpanContext pass through unchanged (no attributes added).

Types

type Format

type Format int

Format selects the slog handler shape.

const (
	// FormatAuto picks JSON when KUBERNETES_SERVICE_HOST is set
	// (i.e. running inside a pod), otherwise text. This is the
	// usual choice for code that runs both locally and in-cluster.
	FormatAuto Format = iota
	// FormatText forces slog.TextHandler.
	FormatText
	// FormatJSON forces slog.JSONHandler.
	FormatJSON
)

type Option added in v0.2.0

type Option func(*config)

Option configures Init. The zero set of options produces a logger writing to os.Stderr at slog.LevelInfo with auto-detected format.

func WithExtraHandlers added in v0.2.0

func WithExtraHandlers(handlers ...slog.Handler) Option

WithExtraHandlers attaches additional slog.Handler sinks that receive every log record alongside the env-selected primary handler. Use them to mirror records to additional sinks — e.g. a JSON handler on os.Stderr kept on top of OTLP for `kubectl logs` debugging, a file handler for an audit trail, or a secondary OTel collector bridge. Each handler's Enabled is checked per record so extras can filter independently of the primary's level.

ExtraHandlers' lifecycles are the caller's responsibility — the Shutdown returned by Init does not close them. Pass handlers over io.Writers that the caller owns (os.Stderr, an open *os.File) rather than ones that need closing.

Stdlib slog handlers (JSONHandler, TextHandler) ignore ctx for trace data. Wrap an extra with WithTraceContextAttrs to inject trace_id / span_id from the active SpanContext on each record.

func WithFormat added in v0.2.0

func WithFormat(f Format) Option

WithFormat overrides FormatAuto. Use FormatText to force text on a pod-deployed binary (rare), or FormatJSON to force JSON in local dev.

func WithLevel added in v0.2.0

func WithLevel(level slog.Level) Option

WithLevel sets the minimum slog level emitted by the non-OTLP handler. Defaults to slog.LevelInfo. OTLP mode is not affected — otelslog.Handler.Enabled defers to the LoggerProvider; configure OTLP-side filtering via the OTel SDK.

func WithLoggerName added in v0.2.0

func WithLoggerName(name string) Option

WithLoggerName identifies the instrumentation scope on emitted OTel LogRecords (OTel SDK's InstrumentationScope.Name). Conventionally the importing module path, e.g. "github.com/giantswarm/muster". Empty falls back to the LoggerProvider's default scope name, which is rarely useful as a Loki filter. OTLP mode only.

func WithOutput added in v0.2.0

func WithOutput(w io.Writer) Option

WithOutput sets the io.Writer that the non-OTLP handler writes to. Nil and unset both mean os.Stderr.

func WithResourceOptions added in v0.2.0

func WithResourceOptions(opts ...resource.Option) Option

WithResourceOptions appends resource.Option values to the toolkit's resource.New option list. Use to add extra attributes (deployment.environment, custom labels) or detectors (k8s, AWS, GCP). The toolkit's own options — semconv ServiceName/Version, Process, OS, Container, FromEnv — are applied first; caller-supplied options follow. OTLP mode only.

func WithServiceName added in v0.2.0

func WithServiceName(name string) Option

WithServiceName sets semconv.ServiceName on the OTLP LoggerProvider's Resource. OTEL_SERVICE_NAME / OTEL_RESOURCE_ATTRIBUTES take precedence. OTLP mode only.

func WithServiceVersion added in v0.2.0

func WithServiceVersion(version string) Option

WithServiceVersion sets semconv.ServiceVersion on the OTLP LoggerProvider's Resource. There is no OTEL_SERVICE_VERSION env var; pass the build version here or in OTEL_RESOURCE_ATTRIBUTES. OTLP mode only.

func WithStderrMirror added in v0.2.1

func WithStderrMirror() Option

WithStderrMirror, in OTLP mode, appends a slog.JSONHandler on os.Stderr (wrapped with WithTraceContextAttrs so records carry trace_id and span_id) to the ExtraHandlers list.

Init returns an error when applied without OTLP logs configured (none of OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, OTEL_EXPORTER_OTLP_ENDPOINT, or OTEL_LOGS_EXPORTER set): the non-OTLP primary already writes to os.Stderr, so a second sink would double-emit.

Honours WithLevel.

type Shutdown added in v0.2.0

type Shutdown func(ctx context.Context) error

Shutdown drains the LoggerProvider on graceful exit. In non-OTLP modes it is a no-op closure; in OTLP mode it forwards to LoggerProvider.Shutdown, which is itself safe to call more than once and from multiple goroutines.

func Init deprecated added in v0.2.0

func Init(ctx context.Context, opts ...Option) (*slog.Logger, Shutdown, error)

Init returns an *slog.Logger and a Shutdown that drains the LoggerProvider on graceful exit.

Init must be called at most once per process. A second call installs a new global LoggerProvider, leaving the first one's BatchProcessor goroutine running with no way to recover a reference for shutdown.

When OTLP logs are configured (any of OTEL_EXPORTER_OTLP_LOGS_ENDPOINT, OTEL_EXPORTER_OTLP_ENDPOINT, or OTEL_LOGS_EXPORTER is set), the primary handler is an otelslog.Handler wired to an OTel LoggerProvider with a BatchProcessor and an autoexport-selected exporter. The provider is also registered as the global OTel LoggerProvider so any code that emits OTel logs directly (e.g. via otel.Logger) routes through it. Records carry the active span's TraceID and SpanID automatically (the OTel SDK pulls SpanContext from the call's context.Context). WithStderrMirror, if applied, synthesises an additional slog.JSONHandler on os.Stderr and appends it to the ExtraHandlers list — see its godoc.

Otherwise the primary handler is JSON inside a Kubernetes pod (KUBERNETES_SERVICE_HOST set), text otherwise, with no OTLP pipeline — the Shutdown is a no-op closure.

WithExtraHandlers, when applied, fans out alongside the primary — every record reaches the primary plus each extra. This is how to keep stderr alive in OTLP mode (pass a slog.NewJSONHandler(os.Stderr, nil) as an extra), tee to a file, or mirror to a secondary backend. Both modes honour ExtraHandlers.

Callers that need to wrap the underlying handler (a domain subsystem layer, attribute redaction, etc.) can call Logger.Handler() on the returned value.

Option applicability:

  • WithFormat, WithOutput apply only to the non-OTLP primary handler. OTLP routes records to the LoggerProvider, not to a writer; the primary handler in OTLP mode is always otelslog.Handler, regardless of WithFormat.
  • WithLevel applies to the non-OTLP primary handler and to the stderr handler added by WithStderrMirror (when present). otelslog.Handler's Enabled defers to the OTel LoggerProvider, not to slog's Level filter; configure OTLP-side filtering via the OTel SDK.
  • WithLoggerName, WithServiceName, WithServiceVersion, WithResourceOptions apply only to OTLP mode.
  • WithStderrMirror requires OTLP mode and returns an error otherwise.
  • WithExtraHandlers applies in both modes.

The OTLP path requires neither traces nor metrics to be configured — the three signals are independent.

Deprecated: Use github.com/giantswarm/mcp-toolkit/telemetry/logging.Init.

Example (Basic)

ExampleInit_basic shows the typical service composition root: install the logger, defer Shutdown, get OTLP delivery when the operator sets OTEL_EXPORTER_OTLP_LOGS_ENDPOINT or OTEL_LOGS_EXPORTER, otherwise fall back to JSON-on-stderr.

package main

import (
	"context"
	"log/slog"

	"github.com/giantswarm/mcp-toolkit/logging"
)

func main() {
	logger, shutdown, err := logging.Init(context.Background(),
		logging.WithLevel(slog.LevelInfo),
		logging.WithLoggerName("github.com/giantswarm/your-mcp"),
		logging.WithServiceName("your-mcp"),
		logging.WithServiceVersion("1.2.3"),
	)
	if err != nil {
		panic(err)
	}
	defer func() { _ = shutdown(context.Background()) }()

	slog.SetDefault(logger)
	slog.Info("ready")
}
Example (FileAuditLog)

ExampleInit_fileAuditLog shows a file handler kept alongside the primary handler, e.g. for an audit trail that must remain on local disk regardless of OTLP delivery status.

The file's lifecycle is the caller's responsibility — the toolkit's Shutdown does not close ExtraHandlers' underlying io.Writers.

package main

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

	"github.com/giantswarm/mcp-toolkit/logging"
)

func main() {
	auditFile, err := os.OpenFile("/var/log/your-mcp/audit.log",
		os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
	if err != nil {
		panic(err)
	}
	defer func() { _ = auditFile.Close() }()

	auditHandler := slog.NewJSONHandler(auditFile, &slog.HandlerOptions{
		Level: slog.LevelInfo,
	})
	logger, shutdown, err := logging.Init(context.Background(),
		logging.WithLevel(slog.LevelInfo),
		logging.WithLoggerName("github.com/giantswarm/your-mcp"),
		logging.WithServiceName("your-mcp"),
		logging.WithServiceVersion("1.2.3"),
		logging.WithExtraHandlers(auditHandler),
	)
	if err != nil {
		panic(err)
	}
	defer func() { _ = shutdown(context.Background()) }()

	logger.Info("authenticated",
		slog.String("subject", "alice"),
		slog.String("action", "list_pods"),
	)
}
Example (OtlpWithStderrMirror)

ExampleInit_otlpWithStderrMirror shows the "OTLP for Loki, stderr for kubectl logs" pattern: when OTLP is configured, records flow to the LoggerProvider; the extra JSON handler keeps a stderr stream alive so an operator running `kubectl logs your-pod` still sees log lines without round-tripping through the collector.

The stderr handler is wrapped in WithTraceContextAttrs so the emitted records carry trace_id and span_id slog.Attrs — the OTLP primary attaches SpanContext to its native OTel LogRecord, but a plain JSONHandler does not read ctx for trace data. Wrapping it gives the stderr stream the same correlation surface Loki gets.

In the non-OTLP fallback the primary handler is already writing to stderr; the extra handler doubles the stream, which is usually undesired in local dev. Gate the extra on a build flag or env var if both modes share a single bootstrap.

package main

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

	"github.com/giantswarm/mcp-toolkit/logging"
)

func main() {
	stderrHandler := logging.WithTraceContextAttrs(
		slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{
			Level: slog.LevelInfo,
		}),
	)
	logger, shutdown, err := logging.Init(context.Background(),
		logging.WithLevel(slog.LevelInfo),
		logging.WithLoggerName("github.com/giantswarm/your-mcp"),
		logging.WithServiceName("your-mcp"),
		logging.WithServiceVersion("1.2.3"),
		logging.WithExtraHandlers(stderrHandler),
	)
	if err != nil {
		panic(err)
	}
	defer func() { _ = shutdown(context.Background()) }()

	logger.Info("ready")
}
Example (WarningOnlyExtra)

ExampleInit_warningOnlyExtra shows that ExtraHandlers can filter independently of the primary. Here the primary handler (OTLP when configured, JSON-on-stderr otherwise) receives everything; the extra writes only Warn-and-above into an in-memory buffer that a supervising process might later inspect or ship.

package main

import (
	"bytes"
	"context"
	"log/slog"

	"github.com/giantswarm/mcp-toolkit/logging"
)

func main() {
	var buf bytes.Buffer
	warningHandler := slog.NewJSONHandler(&buf, &slog.HandlerOptions{
		Level: slog.LevelWarn,
	})
	logger, shutdown, err := logging.Init(context.Background(),
		logging.WithLevel(slog.LevelInfo),
		logging.WithLoggerName("github.com/giantswarm/your-mcp"),
		logging.WithServiceName("your-mcp"),
		logging.WithServiceVersion("1.2.3"),
		logging.WithExtraHandlers(warningHandler),
	)
	if err != nil {
		panic(err)
	}
	defer func() { _ = shutdown(context.Background()) }()

	logger.Info("informational, goes to primary only")
	logger.Warn("warning, primary AND buf")
}

Jump to

Keyboard shortcuts

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