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
- Variables
- func AppendTraceKeyvals(ctx context.Context, keyvals []any) []any
- func ContextWithLogger(ctx context.Context, logger ForLogging) context.Context
- func LevelString(level Level) string
- func LogLogger(logger ForLogging) *log.Logger
- func LogLoggerWithLevel(logger ForLogging, level Level) *log.Logger
- func TraceKeyvalsFromContext(ctx context.Context) []any
- func WriteToLogger(logger ForLogging, p []byte) (int, error)
- type ForLogging
- type Level
- type MinimalSubset
- type Subset
Constants ¶
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 ¶
var DTGTimeFormat string = "021504"
DTGTimeFormat is the default Date Time Group layout (DDHHMM) for console logging.
Functions ¶
func AppendTraceKeyvals ¶ added in v0.13.0
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 ¶
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
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 ¶
LevelFromEnv looks up key in the environment and parses it into a Level.
func LevelFromSlog ¶
LevelFromSlog translates a slog.Level into the closest logport Level.
func ParseLevel ¶
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.