logport

package module
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2025 License: MIT Imports: 9 Imported by: 2

README

logport

logport defines a flexible logging port for Go and ships adapters for the popular structured logging back ends. Your code targets a single, rich façade while you remain free to swap concrete loggers per deployment or integration.

Why logport?
  • Broader interface, consistent ergonomics. Unlike tiny façades, logport embraces the conveniences real applications depend on: key/value logging, printf helpers, context propagation, environment-driven level selection, slog.Handler compatibility, and bridges to the standard library. Every adapter implements the full surface so callers keep identical ergonomics regardless of backend.
  • Performance without ceremony. The native PSL adapter builds on pkt.systems/pslog v0.3.0. It caches timestamp state, promotes trusted keys when you call With, and keeps the hot path allocation-free. Static fields live on the logger (mirroring how the benchmark suite pre-attaches dataset constants), dynamic payloads stay variadic, and pslog.Keyvals is available when you need to pre-promote runtime slices.
  • Adapter breadth. Whether you need zerolog for ingestion, zap for its ecosystem, charm/log for developer-friendly consoles, slog for standard library integrations, or phuslu/log/onelog for lean pipelines, logport ships native adapters so the façade stays unchanged.
  • Transparent trade-offs. Logport focuses on the call site. Rotation, sampling, metrics, and distributed configuration remain the domain of the adapters or downstream sinks. Pick the backend that provides the behaviour you need without refactoring every caller.

Highlights

  • Structured logging support via With, WithGroup, and full slog.Handler compliance (including direct consumption of slog.Attr).
  • Convenience *f helpers (Debugf, Infof, …) for formatted messages, while key/value methods remain allocation-free.
  • WithTrace(ctx) surfaces OpenTelemetry trace_id / span_id pairs across adapters.
  • Level helpers (Trace through Panic) plus LogLevel, LogLevelFromEnv, and WithLogLevel for runtime control and auditability.
  • Native adapters for charmbracelet/log, phuslu/log, rs/zerolog, onelog, go.uber.org/zap, Go’s log/slog, and the zero-allocation PSL adapter.

Quick start

package main

import (
    "context"
    "net/http"
    "os"

    port "pkt.systems/logport"
    psl "pkt.systems/logport/adapters/psl"
    charmlogger "pkt.systems/logport/adapters/charmlogger"
    onelogger "pkt.systems/logport/adapters/onelogger"
)

func main() {
    // Build a PSL console logger once and attach static fields up front.
    logger := psl.New(os.Stderr).With("component", "worker")
    logger.Info("ready", "addr", ":8080")

    // Zero-allocation structured output.
    jsonLogger := psl.NewStructured(os.Stderr).
        With("component", "worker").
        WithLogLevel()
    jsonLogger.Info("ready", "addr", ":8080")

    // Propagate PSL through a context and recover it downstream.
    ctx := port.ContextWithLogger(context.Background(), logger)
    doWork(ctx)

    // Wrap PSL in the stdlib logger for legacy integrations.
    std := port.LogLogger(psl.New(os.Stderr))
    std.Println("legacy library ready")

    // Pin net/http's ErrorLog to ErrorLevel while still stripping prefixes.
    httpErr := port.LogLoggerWithLevel(psl.New(os.Stderr), port.ErrorLevel)
    srv := &http.Server{Addr: ":8080", ErrorLog: httpErr}
    go srv.ListenAndServe()

    // Swap adapters without touching call sites.
    charm := charmlogger.New(os.Stderr).With("component", "worker")
    charm.Warn("slow response", "duration", "120ms")

    minimal := onelogger.New(os.Stderr).With("component", "worker")
    minimal.Info("ready", "addr", ":8080")

    // Derive a debug logger without mutating the original.
    debug := logger.LogLevel(port.DebugLevel)
    debug.Trace("payload", "payload", map[string]any{"a": 1})

    // Promote level from the environment and surface it in output.
    runtimeLogger := logger.LogLevelFromEnv("APP_LOG_LEVEL").WithLogLevel()
    runtimeLogger.Info("running", "pid", os.Getpid())
}

func doWork(ctx context.Context) {
    port.LoggerFromContext(ctx).WithTrace(ctx).Info("processing", "job", 42)
}
Performance-minded usage
  • Static fields: attach non-changing fields via With during construction. PSL promotes those key/value pairs and skips escape checks on subsequent logs.
  • Dynamic payloads: pass per-call values directly. For reusable runtime slices, call pslog.Keyvals(dynamic...) once.
  • Timestamps: PSL caches formatted timestamps by layout; disable them with Options{DisableTimestamp: true} when chasing every nanosecond.
OpenTelemetry traces
ctx, span := tracer.Start(ctx, "work")
defer span.End()

logger.WithTrace(ctx).Info("handled request")
Stdlib compatibility

Every adapter implements io.Writer, making it trivial to share the logger with packages that expect a writer, including log.Logger. logport.LogLogger returns a prefix-free *log.Logger, and logport.LogLoggerWithLevel pins every write to a specific severity while still stripping redundant prefixes.

Minimal subsets

ForLogging embeds MinimalSubset (Debug/Info/Warn/Error). Depend on the minimal subset when you only need basic logging; all adapters implement it, and bespoke loggers can satisfy just those methods to participate.

Runtime level control

LogLevelFromEnv recognises trace, debug, info, warn, warning, error, fatal, panic, no, nolevel, disabled, and off. Pair it with WithLogLevel() to embed the selected level. Prefer Logp for programmatic levels, Logs for textual severities, and Logf/*f helpers for formatted output.

Log levels

Name Description
TraceLevel Fine-grained diagnostics below debug.
DebugLevel Development diagnostics.
InfoLevel Routine operational messages.
WarnLevel Non-fatal issues that require attention.
ErrorLevel Failures handled within the process.
FatalLevel Logs and exits (status 1).
PanicLevel Logs and panics.
NoLevel Emits entries without severity when supported.
Disabled Turns logging off.

NoLevel behaviour per adapter

Adapter Behaviour
Charmbracelet Reuses Print; message/fields emitted without level.
phuslu/log Uses logger.Log() to omit the level key.
zerolog JSON Emits JSON without a level field.
zerolog Console Displays zerolog’s placeholder.
zap Maps NoLevel to Debug (zap lacks a native level-less mode).

Adapter notes

  • onelogger – timestamps default to port.DTGTimeFormat; customise with Options{TimeFormat: ...} or disable via Options{DisableTimestamp: true}.
  • zerologger – use NewStructured/Options{Structured: true} for JSON, Options{DisableTimestamp: true} to drop timestamps.
  • slogger – New for text, NewJSON for structured output, or wrap custom handlers via NewWithHandler/NewWithLogger.
  • charmlogger – New for colourful console output or NewStructured for JSON (log.JSONFormatter).
  • psl – the native adapter built on pslog v0.3.0. It caches timestamps, promotes trusted keys during With, supports colourful JSON via Options{ColorJSON: true}, expands JSON keys with Options{VerboseFields: true} (ts/lvl/msg → time/level/message), and forces UTC with Options{UTC: true}.
  • zaplogger – tracks the configured level so WithLogLevel() reflects the underlying zap core after environment overrides or chained With calls.

Panic and fatal helpers

Fatal logs and terminates (os.Exit(1)); Panic logs then panics, matching each backend.

Context integration

ContextWithLogger / LoggerFromContext stash and recover adapters inside a context.Context, so per-request workflows can reuse the same logger without plumbing it through every call.

Benchmark suite

The repository includes a standalone module under benchmark/. It uses a production log dataset to exercise each adapter/native logger in two modes:

  • ProductionDataset – every logger attaches shared static fields via .With(...), emits its native timestamp/level metadata, and logs the full dynamic payload at TraceLevel.
  • ProductionDatasetNoTimestamp – the same workload but with every logger’s timestamp feature disabled to isolate the hot path without time formatting.

Run the suite with:

go test ./benchmark -bench=. -run=^$ -benchmem

On a 13th-gen Intel® i7 laptop (Go 1.25), the structured adapters land in the same payload range once the static fields are pre-attached. Representative numbers:

Benchmark (timestamps on) ns/op bytes/op B/op allocs/op
phuslu/json 212 416.7 0 0
psl/json 244 408.7 0 0
zerolog/json 328 416.7 4 0
zap/json 1095 413.7 548 1
slog/json (Go 1.25 handler) 1215 422.6 466 1

The ...NoTimestamp benchmark drops each logger’s time field (PSL’s cached layout, Zerolog’s Timestamp(), Zap’s ISO-8601 ts, slog’s time, etc.) so you can compare the raw formatter overhead without time formatting.

Heads-up: Some loggers (e.g. Charm v0.4) deliberately keep their JSON schema minimal, so their payloads will be shorter than pslog’s, which emits a compact ts/lvl alias alongside the main fields.

Testing

go test ./...

Adapter tests cover NoLevel behaviour, level derivation, environment overrides, standard library bridges, tracing helpers, and the zero-allocation paths to guard against regressions.

Documentation

Overview

Package logport defines a minimal logging port that can be satisfied by multiple back ends. The core ForLogging interface embeds slog.Handler so that adapters can be used both as structured logging receivers and as drop-in slog handlers and much more.

Typical usage pairs the port with one of the provided adapters:

logger := zerologger.New(os.Stdout)
logger.Info("Ready", "addr", addr)

or, when a context-based workflow is preferred:

ctx := port.ContextWithLogger(context.Background(), charmlogger.New(os.Stdout))
l := port.LoggerFromContext(ctx)
l.With("request_id", "abc-123").Warn("slow response", "duration", took)

Because adapters implement slog.Handler, they can also be passed directly to slog.New:

slogLogger := slog.New(zerologger.New(os.Stdout))
slogLogger.Info("hello from slog", slog.String("component", "worker"))

Index

Constants

View Source
const (
	// TraceIDKey is the structured logging key used to store OpenTelemetry trace IDs.
	TraceIDKey = "trace_id"
	// SpanIDKey is the structured logging key used to store OpenTelemetry span IDs.
	SpanIDKey = "span_id"
)

Variables

View Source
var DTGTimeFormat string = "021504"

DTGTimeFormat is the default Date Time Group layout (DDHHMM) for console logging.

Functions

func AppendTraceKeyvals added in v0.13.0

func AppendTraceKeyvals(ctx context.Context, keyvals []any) []any

AppendTraceKeyvals returns a slice that includes trace identifiers extracted from ctx (when present) followed by the supplied keyvals. When ctx does not carry a valid span context, keyvals is returned unchanged.

func ContextWithLogger

func ContextWithLogger(ctx context.Context, logger ForLogging) context.Context

ContextWithLogger returns a child context carrying the supplied logger implementation.

func LevelString

func LevelString(level Level) string

LevelString returns the canonical string representation of a Level.

func LogLogger added in v0.10.0

func LogLogger(logger ForLogging) *log.Logger

LogLogger wraps a ForLogging implementation into a stdlib *log.Logger.

func LogLoggerWithLevel added in v0.11.0

func LogLoggerWithLevel(logger ForLogging, level Level) *log.Logger

LogLoggerWithLevel wraps a ForLogging implementation into a stdlib *log.Logger that pins every emitted entry to level. The wrapped logger still benefits from prefix classification to strip level tokens from msg, but the detected level is ignored in favour of the supplied one.

func TraceKeyvalsFromContext added in v0.13.0

func TraceKeyvalsFromContext(ctx context.Context) []any

TraceKeyvalsFromContext extracts OpenTelemetry trace identifiers from ctx and returns them as alternating key/value pairs using TraceIDKey and SpanIDKey. When ctx does not contain a valid span context, the returned slice is nil.

func WriteToLogger added in v0.10.0

func WriteToLogger(logger ForLogging, p []byte) (int, error)

WriteToLogger routes bytes to logger.Logp, splitting on newlines and detecting severity prefixes. It always reports len(p) to comply with io.Writer semantics.

Types

type ForLogging

type ForLogging interface {
	slog.Handler
	io.Writer

	// LogLevelFromEnv configures the logger's level using the value of key in the
	// environment. Recognised values are the same as ParseLevel. Missing or
	// invalid values leave the logger unchanged.
	LogLevelFromEnv(key string) ForLogging

	// LogLevel returns a logger derived from the receiver whose minimum level is
	// set to level. The receiver itself is not modified.
	LogLevel(Level) ForLogging

	// WithLogLevel returns a logger that carries a `loglevel` field describing
	// the logger's effective severity.
	WithLogLevel() ForLogging

	// With returns a logger that includes the supplied key/value pairs on every
	// subsequent log entry. The receiver remains untouched.
	With(keyvals ...any) ForLogging

	// WithTrace utilizes otel/trace to add trace_id and span_id keyvals to the
	// logger derived from an OpenTelemetry span context (set by
	// otel.Tracer("...").Start(origCtx, "...").
	//
	// Example:
	//
	//	tracer := otel.Tracer("worker")
	//	func handle(ctx context.Context, logger logport.ForLogging) {
	//		ctx, span := tracer.Start(ctx, "handle")
	//		defer span.End()
	//
	//		logger.WithTrace(ctx).With("component", "api").Info("processing request")
	//	}
	//
	// The returned logger includes "trace_id" and "span_id" keyvals when the
	// context carries a valid OpenTelemetry span.
	WithTrace(ctx context.Context) ForLogging

	Subset

	// Logp emits msg at the supplied logport level.
	Logp(level Level, msg string, keyvals ...any)

	// Logf formats msg using fmt.Sprintf semantics and logs it at the supplied
	// logport level.
	Logf(level Level, format string, v ...any)

	// Debugf logs a formatted message at DebugLevel.
	Debugf(format string, v ...any)
	// Infof logs a formatted message at InfoLevel.
	Infof(format string, v ...any)
	// Warnf logs a formatted message at WarnLevel.
	Warnf(format string, v ...any)
	// Errorf logs a formatted message at ErrorLevel.
	Errorf(format string, v ...any)
	// Fatalf logs a formatted message at FatalLevel.
	Fatalf(format string, v ...any)
	// Panicf logs a formatted message at PanicLevel.
	Panicf(format string, v ...any)
	// Tracef logs a formatted message at TraceLevel.
	Tracef(format string, v ...any)
}

ForLogging is a logger with superpowers wrapping several logging backends that plug in as adapters to this port. Prefer the structured helpers over the *f variants when you need maximum efficiency; the formatting versions allocate for convenience when ergonomics matter more than throughput.

func LoggerFromContext

func LoggerFromContext(ctx context.Context) ForLogging

LoggerFromContext extracts a logger implementation from context if present or returns a NoopLogger.

func NoopLogger

func NoopLogger() ForLogging

NoopLogger provides a logger implementation that discards all log messages.

type Level

type Level int8

Level defines log levels.

const (
	// DebugLevel defines debug log level.
	DebugLevel Level = iota
	// InfoLevel defines info log level.
	InfoLevel
	// WarnLevel defines warn log level.
	WarnLevel
	// ErrorLevel defines error log level.
	ErrorLevel
	// FatalLevel defines fatal log level.
	FatalLevel
	// PanicLevel defines panic log level.
	PanicLevel
	// NoLevel defines an absent log level.
	NoLevel
	// Disabled disables the logger.
	Disabled
	// TraceLevel defines trace log level.
	TraceLevel Level = -1
)

func LevelFromEnv

func LevelFromEnv(key string) (Level, bool)

LevelFromEnv looks up key in the environment and parses it into a Level.

func LevelFromSlog

func LevelFromSlog(level slog.Level) Level

LevelFromSlog translates a slog.Level into the closest logport Level.

func ParseLevel

func ParseLevel(value string) (Level, bool)

ParseLevel converts a textual level into a Level value. It accepts values such as "trace", "debug", "info", "warn", "warning", "error", "fatal", "panic", "no", "nolevel", "disabled", and "off" (case insensitive).

type MinimalSubset added in v0.16.0

type MinimalSubset interface {
	// Debug logs msg at DebugLevel.
	Debug(msg string, keyvals ...any)
	// Info logs msg at InfoLevel.
	Info(msg string, keyvals ...any)
	// Warn logs msg at WarnLevel.
	Warn(msg string, keyvals ...any)
	// Error logs msg at ErrorLevel.
	Error(msg string, keyvals ...any)
}

MinimalSubset defines the smallest set of convenience methods that library authors can require when they want consumers to plug in their own logger. Callers can satisfy this interface with a bespoke implementation or by reusing a logport adapter.

type Subset added in v0.16.0

type Subset interface {
	MinimalSubset

	// Trace logs msg at TraceLevel (below DebugLevel).
	Trace(msg string, keyvals ...any)
	// Fatal logs msg at FatalLevel and terminates the process when the backend
	// supports it.
	Fatal(msg string, keyvals ...any)
	// Panic logs msg at PanicLevel and panics when the backend supports it.
	Panic(msg string, keyvals ...any)
	// Log mirrors slog.Logger.Log and emits msg at the provided slog level using
	// the supplied context and key/value pairs.
	Log(ctx context.Context, level slog.Level, msg string, keyvals ...any)
	// Logs emits msg using the level encoded in the string. Unknown or empty
	// values fall back to NoLevel semantics.
	Logs(level string, msg string, keyvals ...any)
}

Subset extends the minimal contract with additional helpers for libraries that need trace, panic, fatal, or slog-compatible logging while still allowing API users to bring their own logger or any adapter that implements these methods.

Directories

Path Synopsis
adapters
psl

Jump to

Keyboard shortcuts

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