logr

package module
v0.0.0-...-93f8639 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2025 License: MIT Imports: 4 Imported by: 0

README

mtlog logr Adapter

This module provides a logr adapter for mtlog, enabling Kubernetes controllers and operators to use mtlog's powerful structured logging features while maintaining full compatibility with the logr API.

Installation

go get github.com/willibrandon/mtlog/adapters/logr

Quick Start

import (
    "github.com/willibrandon/mtlog"
    mtlogr "github.com/willibrandon/mtlog/adapters/logr"
    "github.com/willibrandon/mtlog/core"
)

// Create a logr logger backed by mtlog
logger := mtlogr.NewLogger(
    mtlog.WithConsole(),
    mtlog.WithMinimumLevel(core.DebugLevel),
)

// Use standard logr API
logger.Info("starting reconciliation", "namespace", "default", "name", "my-app")
logger.V(1).Info("detailed info", "replicas", 3)
logger.Error(err, "failed to update resource", "reason", "conflict")

Features

  • Full logr Compatibility: Drop-in replacement for any logr backend
  • Message Templates: Leverage mtlog's powerful message template system
  • Rich Sinks: Output to Console, Seq, Elasticsearch, Splunk, and more
  • Pipeline Architecture: Add enrichers, filters, and capturers
  • Performance: Benefit from mtlog's optimized logging pipeline

V-Level Mapping

logr V-levels are mapped to mtlog levels:

logr V-level mtlog Level Description
V(0) Information Standard info messages
V(1) Debug Debug-level details
V(2+) Verbose Highly verbose output

Advanced Usage

Custom Configuration
// Create mtlog logger with custom configuration
mtlogLogger := mtlog.New(
    mtlog.WithSeq("http://localhost:5341"),
    mtlog.WithProperty("service", "my-controller"),
    mtlog.WithEnricher(enrichers.WithMachineName()),
    mtlog.WithFilter(filters.ByIncludingOnly(func(e core.LogEvent) bool {
        return e.Level >= core.InformationLevel
    })),
)

// Create logr logger from custom mtlog instance
logrLogger := logr.New(mtlogr.NewLogrSink(mtlogLogger))
With Kubernetes Controller Runtime
import (
    "sigs.k8s.io/controller-runtime/pkg/log"
    "sigs.k8s.io/controller-runtime/pkg/log/zap"
)

func main() {
    // Set mtlog as the global logger for controller-runtime
    log.SetLogger(mtlogr.NewLogger(
        mtlog.WithConsole(),
        mtlog.WithProperty("component", "manager"),
    ))
    
    // Your controller setup...
}
Structured Logging Best Practices
logger := mtlogr.NewLogger(mtlog.WithConsole())

// Good: Use consistent key names
logger.Info("pod created", 
    "namespace", pod.Namespace,
    "name", pod.Name,
    "phase", pod.Status.Phase,
)

// Use WithValues for persistent context
reqLogger := logger.WithValues("request_id", requestID)
reqLogger.Info("handling request")
reqLogger.Info("request completed", "duration_ms", duration.Milliseconds())

// Use WithName for component hierarchy
controllerLog := logger.WithName("controller").WithName("deployment")
controllerLog.Info("reconciling", "generation", deployment.Generation)

Performance

The adapter maintains mtlog's high performance while providing logr compatibility:

  • Zero allocations for disabled log levels
  • Efficient property handling
  • Batched output to remote sinks
  • Minimal overhead for the adapter layer

License

MIT License - same as mtlog

Documentation

Overview

Package logr provides an adapter that allows mtlog to be used as a backend for logr, the structured logging interface used throughout the Kubernetes ecosystem.

This adapter enables Kubernetes controllers and operators to leverage mtlog's powerful features including message templates, pipeline architecture, and rich sink ecosystem while maintaining compatibility with logr's API.

Basic Usage

Create a logr.Logger backed by mtlog:

import (
    "github.com/willibrandon/mtlog"
    mtlogr "github.com/willibrandon/mtlog/adapters/logr"
)

logger := mtlogr.NewLogger(
    mtlog.WithConsole(),
    mtlog.WithMinimumLevel(core.DebugLevel),
)

// Use standard logr API
logger.Info("reconciling", "namespace", "default", "name", "my-app")
logger.Error(err, "failed to update resource")

V-Level Mapping

logr V-levels are mapped to mtlog levels as follows:

  • V(0) → Information
  • V(1) → Debug
  • V(2+) → Verbose

Advanced Usage

For more control, create a custom sink:

mtlogLogger := mtlog.New(
    mtlog.WithSeq("http://localhost:5341"),
    mtlog.WithProperty("service", "my-controller"),
)
logrLogger := logr.New(mtlogr.NewLogrSink(mtlogLogger))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewLogger

func NewLogger(options ...mtlog.Option) logr.Logger

NewLogger creates a new logr.Logger backed by mtlog.

This is the simplest way to create a logr logger that writes to mtlog. All standard mtlog options can be passed to configure the underlying logger, including sinks, enrichers, filters, and minimum level.

Example:

logger := mtlogr.NewLogger(
    mtlog.WithConsole(),
    mtlog.WithSeq("http://localhost:5341"),
    mtlog.WithProperty("app", "my-service"),
    mtlog.WithMinimumLevel(core.DebugLevel),
)

Types

type LogrSink

type LogrSink struct {
	// contains filtered or unexported fields
}

LogrSink implements logr.LogSink backed by mtlog's logger.

This sink adapts logr's logging interface to mtlog's structured logging pipeline, preserving all the power of mtlog while maintaining full compatibility with logr.

The sink handles:

  • V-level mapping to mtlog levels (V0→Info, V1→Debug, V2+→Verbose)
  • Key/value pair conversion to mtlog properties
  • Logger name hierarchies (controller.reconciler)
  • Persistent values via WithValues
  • Error logging with proper error context

func NewLogrSink

func NewLogrSink(logger core.Logger) *LogrSink

NewLogrSink creates a new logr.LogSink that writes to the provided mtlog logger.

The returned sink can be passed to logr.New() to create a logr.Logger:

mtlogLogger := mtlog.New(mtlog.WithConsole())
logrLogger := logr.New(mtlogr.NewLogrSink(mtlogLogger))

All log events from logr will be processed through mtlog's pipeline, including enrichment, filtering, capturing, and output to configured sinks.

func (*LogrSink) Enabled

func (s *LogrSink) Enabled(level int) bool

Enabled tests whether this LogSink is enabled at the given V-level.

V-levels are mapped as follows:

  • V(0) → Information (always enabled unless filtered)
  • V(1) → Debug
  • V(2+) → Verbose

This allows fine-grained control over verbosity using mtlog's level system.

func (*LogrSink) Error

func (s *LogrSink) Error(err error, msg string, keysAndValues ...interface{})

Error logs an error message with the given key/value pairs.

The error is added to the log event context under the "error" property, and the message is logged at Error level. All key/value pairs are included as properties.

func (*LogrSink) Info

func (s *LogrSink) Info(level int, msg string, keysAndValues ...interface{})

Info logs a non-error message with the given key/value pairs.

The message is logged at the appropriate mtlog level based on the V-level. All key/value pairs (both persistent values and those passed here) are added as properties to the log event.

func (*LogrSink) Init

func (s *LogrSink) Init(info logr.RuntimeInfo)

Init receives optional information about the logr library for the LogSink.

Currently this is a no-op as mtlog handles caller information through its own enrichers (e.g., WithCallers).

func (*LogrSink) WithName

func (s *LogrSink) WithName(name string) logr.LogSink

WithName returns a new LogSink with the specified name appended.

Names create a hierarchy separated by dots. The full logger name is included as the "logger" property in all log events.

Example:

logger = logger.WithName("controller").WithName("reconciler")
logger.Info("starting") // includes logger="controller.reconciler"

func (*LogrSink) WithValues

func (s *LogrSink) WithValues(keysAndValues ...interface{}) logr.LogSink

WithValues returns a new LogSink with additional key/value pairs.

These values will be included in all subsequent log messages from the returned LogSink. This is useful for adding persistent context like request IDs or user information.

Example:

logger = logger.WithValues("request_id", "123", "user", "alice")
logger.Info("processing") // includes request_id and user

Jump to

Keyboard shortcuts

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