mtlog

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2025 License: MIT Imports: 13 Imported by: 16

README

mtlog - Message Template Logging for Go

Go Reference

mtlog is a high-performance structured logging library for Go, inspired by Serilog. It brings message templates and pipeline architecture to the Go ecosystem, achieving zero allocations for simple logging operations while providing powerful features for complex scenarios.

Features

Core Features
  • Zero-allocation logging for simple messages (17.3 ns/op)
  • Message templates with positional property extraction and format specifiers
  • Go template syntax support ({{.Property}}) alongside traditional syntax
  • Output templates for customizable log formatting
  • Source context enrichment with intelligent caching for automatic logger categorization
  • Pipeline architecture for clean separation of concerns
  • Type-safe generics for better compile-time safety
  • LogValue interface for safe logging of sensitive data
  • 7.7x faster than zap for simple string logging
  • Standard library compatibility via slog.Handler adapter (Go 1.21+)
  • Kubernetes ecosystem support via logr.LogSink adapter
Sinks & Output
  • Console sink with customizable themes (dark, light, ANSI, Literate)
  • File sink with rolling policies (size, time-based)
  • Seq integration with CLEF format and dynamic level control
  • Elasticsearch sink for centralized log storage and search
  • Splunk sink with HEC (HTTP Event Collector) support
  • Async sink wrapper for high-throughput scenarios
  • Durable buffering with persistent storage for reliability
Pipeline Components
  • Rich enrichment with built-in and custom enrichers
  • Advanced filtering including rate limiting and sampling
  • Minimum level overrides by source context patterns
  • Type-safe destructuring with caching for performance
  • Dynamic level control with runtime adjustments
  • Configuration from JSON for flexible deployment

Installation

go get github.com/willibrandon/mtlog

Quick Start

package main

import (
    "github.com/willibrandon/mtlog"
    "github.com/willibrandon/mtlog/core"
)

func main() {
    // Create a logger with console output
    log := mtlog.New(
        mtlog.WithConsoleProperties(),
        mtlog.WithMinimumLevel(core.InformationLevel),
    )

    // Simple logging
    log.Information("Application started")
    
    // Message templates with properties
    userId := 123
    log.Information("User {UserId} logged in", userId)
    
    // Destructuring complex types
    order := Order{ID: 456, Total: 99.95}
    log.Information("Processing {@Order}", order)
}

// For libraries that need error handling:
func NewLibraryLogger() (*mtlog.Logger, error) {
    return mtlog.Build(
        mtlog.WithConsoleTemplate("[{Timestamp:HH:mm:ss} {Level:u3}] {Message}"),
        mtlog.WithMinimumLevel(core.DebugLevel),
    )
}

Visual Example

mtlog with Literate theme

Message Templates

mtlog uses message templates that preserve structure throughout the logging pipeline:

// Properties are extracted positionally
log.Information("User {UserId} logged in from {IP}", userId, ipAddress)

// Go template syntax is also supported
log.Information("User {{.UserId}} logged in from {{.IP}}", userId, ipAddress)

// Mix both syntaxes as needed
log.Information("User {UserId} ({{.Username}}) from {IP}", userId, username, ipAddress)

// Destructuring hints:
// @ - destructure complex types into properties
log.Information("Order {@Order} created", order)

// $ - force scalar rendering (stringify)
log.Information("Error occurred: {$Error}", err)

// Format specifiers
log.Information("Processing time: {Duration:F2}ms", 123.456)
log.Information("Disk usage at {Percentage:P1}", 0.85)  // 85.0%
log.Information("Order {OrderId:000} total: ${Amount:F2}", 42, 99.95)

Output Templates

Control how log events are formatted for output with customizable templates:

// Console with custom output template
log := mtlog.New(
    mtlog.WithConsoleTemplate("[{Timestamp:HH:mm:ss} {Level:u3}] {SourceContext}: {Message}"),
    mtlog.WithConsoleTheme(sinks.LiterateTheme()),
)

// File with detailed template
log := mtlog.New(
    mtlog.WithFileTemplate("app.log", 
        "[{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level:u3}] {SourceContext}: {Message}{NewLine}{Exception}"),
)
Template Properties
  • {Timestamp} - Event timestamp with optional format
  • {Level} - Log level with format options (u3, u, l)
  • {Message} - Rendered message from template
  • {SourceContext} - Logger context/category
  • {Exception} - Exception details if present
  • {NewLine} - Platform-specific line separator
  • Custom properties by name: {RequestId}, {UserId}, etc.
Format Specifiers
  • Timestamps: HH:mm:ss, yyyy-MM-dd, HH:mm:ss.fff
  • Levels: u3 (INF), u (INFORMATION), l (information)
  • Numbers: 000 (zero-pad), F2 (2 decimals), P1 (percentage)

Pipeline Architecture

The logging pipeline processes events through distinct stages:

Message Template Parser → Enrichment → Filtering → Destructuring → Output
Configuration with Functional Options
log := mtlog.New(
    // Output configuration
    mtlog.WithConsoleTheme("dark"),     // Console with dark theme
    mtlog.WithRollingFile("app.log", 10*1024*1024), // Rolling file (10MB)
    mtlog.WithSeq("http://localhost:5341", "api-key"), // Seq integration
    
    // Enrichment
    mtlog.WithTimestamp(),              // Add timestamp
    mtlog.WithMachineName(),            // Add hostname
    mtlog.WithProcessInfo(),            // Add process ID/name
    mtlog.WithCallersInfo(),            // Add file/line info
    
    // Filtering & Level Control
    mtlog.WithMinimumLevel(core.DebugLevel),
    mtlog.WithDynamicLevel(levelSwitch), // Runtime level control
    mtlog.WithFilter(customFilter),
    
    // Destructuring
    mtlog.WithDestructuring(),          // Enable @ hints
    mtlog.WithDestructuringDepth(5),    // Max depth
)

Enrichers

Enrichers add contextual information to all log events:

// Built-in enrichers
log := mtlog.New(
    mtlog.WithTimestamp(),
    mtlog.WithMachineName(),
    mtlog.WithProcessInfo(),
    mtlog.WithEnvironmentVariables("APP_ENV", "VERSION"),
    mtlog.WithThreadId(),
    mtlog.WithCallersInfo(),
    mtlog.WithCorrelationId("RequestId"),
    mtlog.WithSourceContext(), // Auto-detect logger context
)

// Context-based enrichment
ctx := context.WithValue(context.Background(), "RequestId", "abc-123")
log.ForContext("UserId", userId).Information("Processing request")

// Source context for sub-loggers
serviceLog := log.ForSourceContext("MyApp.Services.UserService")
serviceLog.Information("User service started")

Filters

Control which events are logged with powerful filtering:

// Level filtering
mtlog.WithMinimumLevel(core.WarningLevel)

// Minimum level overrides by source context
mtlog.WithMinimumLevelOverrides(map[string]core.LogEventLevel{
    "github.com/gin-gonic/gin":       core.WarningLevel,    // Suppress Gin info logs
    "github.com/go-redis/redis":      core.ErrorLevel,      // Only Redis errors
    "myapp/internal/services":        core.DebugLevel,      // Debug for internal services
    "myapp/internal/services/auth":   core.VerboseLevel,    // Verbose for auth debugging
})

// Custom predicate
mtlog.WithFilter(filters.NewPredicateFilter(func(e *core.LogEvent) bool {
    return !strings.Contains(e.MessageTemplate.Text, "health-check")
}))

// Rate limiting
mtlog.WithFilter(filters.NewRateLimitFilter(100, time.Minute))

// Statistical sampling
mtlog.WithFilter(filters.NewSamplingFilter(0.1)) // 10% of events

// Property-based filtering
mtlog.WithFilter(filters.NewExpressionFilter("UserId", 123))

Sinks

mtlog supports multiple output destinations with advanced features:

Console Sink with Themes
// Literate theme - beautiful, easy on the eyes
mtlog.WithConsoleTheme(sinks.LiterateTheme())

// Dark theme (default)
mtlog.WithConsoleTheme(sinks.DarkTheme())

// Light theme
mtlog.WithConsoleTheme(sinks.LightTheme()) 

// Plain text (no colors)
mtlog.WithConsoleTheme(sinks.NoColorTheme())
File Sinks
// Simple file output
mtlog.WithFileSink("app.log")

// Rolling file by size
mtlog.WithRollingFile("app.log", 10*1024*1024) // 10MB

// Rolling file by time
mtlog.WithRollingFileTime("app.log", time.Hour) // Every hour
Seq Integration
// Basic Seq integration
mtlog.WithSeq("http://localhost:5341")

// With API key
mtlog.WithSeq("http://localhost:5341", "your-api-key")

// Advanced configuration
mtlog.WithSeqAdvanced("http://localhost:5341",
    sinks.WithSeqBatchSize(100),
    sinks.WithSeqBatchTimeout(5*time.Second),
    sinks.WithSeqCompression(true),
)

// Dynamic level control via Seq
levelOption, levelSwitch, controller := mtlog.WithSeqLevelControl(
    "http://localhost:5341",
    mtlog.SeqLevelControllerOptions{
        CheckInterval: 30*time.Second,
        InitialCheck: true,
    },
)
Elasticsearch Integration
// Basic Elasticsearch
mtlog.WithElasticsearch("http://localhost:9200", "logs")

// With authentication
mtlog.WithElasticsearchAdvanced(
    []string{"http://localhost:9200"},
    elasticsearch.WithIndex("myapp-logs"),
    elasticsearch.WithAPIKey("api-key"),
    elasticsearch.WithBatchSize(100),
)
Splunk Integration
// Splunk HEC integration
mtlog.WithSplunk("http://localhost:8088", "your-hec-token")

// Advanced Splunk configuration
mtlog.WithSplunkAdvanced("http://localhost:8088",
    sinks.WithSplunkToken("hec-token"),
    sinks.WithSplunkIndex("main"),
    sinks.WithSplunkSource("myapp"),
)
Async and Durable Sinks
// Wrap any sink for async processing
mtlog.WithAsync(mtlog.WithFileSink("app.log"))

// Durable buffering (survives crashes)
mtlog.WithDurable(
    mtlog.WithSeq("http://localhost:5341"),
    sinks.WithDurableDirectory("./logs/buffer"),
    sinks.WithDurableMaxSize(100*1024*1024), // 100MB buffer
)

Dynamic Level Control

Control logging levels at runtime without restarting your application:

Manual Level Control
// Create a level switch
levelSwitch := mtlog.NewLoggingLevelSwitch(core.InformationLevel)

logger := mtlog.New(
    mtlog.WithLevelSwitch(levelSwitch),
    mtlog.WithConsole(),
)

// Change level at runtime
levelSwitch.SetLevel(core.DebugLevel)

// Fluent interface
levelSwitch.Debug().Information().Warning()

// Check if level is enabled
if levelSwitch.IsEnabled(core.VerboseLevel) {
    // Expensive logging operation
}
Centralized Level Control with Seq
// Automatic level synchronization with Seq server
options := mtlog.SeqLevelControllerOptions{
    CheckInterval: 30 * time.Second,
    InitialCheck:  true,
}

loggerOption, levelSwitch, controller := mtlog.WithSeqLevelControl(
    "http://localhost:5341", options)
defer controller.Close()

logger := mtlog.New(loggerOption)

// Level changes in Seq UI automatically update your application

Configuration from JSON

Configure loggers using JSON for flexible deployments:

// Load from JSON file
config, err := configuration.LoadFromFile("logging.json")
if err != nil {
    log.Fatal(err)
}

logger := config.CreateLogger()

Example logging.json:

{
    "minimumLevel": "Information",
    "sinks": [
        {
            "type": "Console",
            "theme": "dark"
        },
        {
            "type": "RollingFile",
            "path": "logs/app.log",
            "maxSize": "10MB"
        },
        {
            "type": "Seq",
            "serverUrl": "http://localhost:5341",
            "apiKey": "${SEQ_API_KEY}"
        }
    ],
    "enrichers": ["Timestamp", "MachineName", "ProcessInfo"]
}

Safe Logging with LogValue

Protect sensitive data with the LogValue interface:

type User struct {
    ID       int
    Username string
    Password string // Never logged
}

func (u User) LogValue() interface{} {
    return map[string]interface{}{
        "id":       u.ID,
        "username": u.Username,
        // Password intentionally omitted
    }
}

// Password won't appear in logs
user := User{ID: 1, Username: "alice", Password: "secret"}
log.Information("User logged in: {@User}", user)

Performance

Benchmark results on AMD Ryzen 9 9950X:

Operation mtlog zap zerolog Winner
Simple string 16.82 ns 146.6 ns 36.46 ns mtlog
Filtered out 1.47 ns 3.57 ns 1.71 ns mtlog
Two properties 190.6 ns 216.9 ns 49.48 ns zerolog
With context 205.2 ns 130.8 ns 35.25 ns zerolog

Examples

See the examples directory for complete examples:

Ecosystem Compatibility

Standard Library (slog)

mtlog provides full compatibility with Go's standard log/slog package:

// Use mtlog as a backend for slog
slogger := mtlog.NewSlogLogger(
    mtlog.WithSeq("http://localhost:5341"),
    mtlog.WithMinimumLevel(core.InformationLevel),
)

// Use standard slog API
slogger.Info("user logged in", "user_id", 123, "ip", "192.168.1.1")

// Or create a custom slog handler
logger := mtlog.New(mtlog.WithConsole())
slogger = slog.New(logger.AsSlogHandler())
Kubernetes (logr)

mtlog integrates with the Kubernetes ecosystem via logr:

// Use mtlog as a backend for logr
logrLogger := mtlog.NewLogrLogger(
    mtlog.WithConsole(),
    mtlog.WithMinimumLevel(core.DebugLevel),
)

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

// Or create a custom logr sink
logger := mtlog.New(mtlog.WithSeq("http://localhost:5341"))
logrLogger = logr.New(logger.AsLogrSink())

Environment Variables

mtlog respects several environment variables for runtime configuration:

Color Control
# Force specific color mode (overrides terminal detection)
export MTLOG_FORCE_COLOR=none     # Disable all colors
export MTLOG_FORCE_COLOR=8        # Force 8-color mode (basic ANSI)
export MTLOG_FORCE_COLOR=256      # Force 256-color mode

# Standard NO_COLOR variable is also respected
export NO_COLOR=1                 # Disable colors (follows no-color.org)
Performance Tuning
# Adjust source context cache size (default: 10000)
export MTLOG_SOURCE_CTX_CACHE=50000  # Increase for large applications
export MTLOG_SOURCE_CTX_CACHE=1000   # Decrease for memory-constrained environments

Advanced Usage

Custom Sinks

Implement the core.LogEventSink interface for custom outputs:

type CustomSink struct{}

func (s *CustomSink) Emit(event *core.LogEvent) error {
    // Process the log event
    return nil
}

log := mtlog.New(
    mtlog.WithSink(&CustomSink{}),
)
Custom Enrichers

Add custom properties to all events:

type UserEnricher struct {
    userID int
}

func (e *UserEnricher) Enrich(event *core.LogEvent, factory core.LogEventPropertyFactory) {
    event.AddPropertyIfAbsent(factory.CreateProperty("UserId", e.userID))
}

log := mtlog.New(
    mtlog.WithEnricher(&UserEnricher{userID: 123}),
)
Type Registration

Register types for special handling during destructuring:

destructurer := destructure.NewDefaultDestructurer()
destructurer.RegisterScalarType(reflect.TypeOf(uuid.UUID{}))

Documentation

For comprehensive guides and examples, see the docs directory:

Testing

# Run unit tests
go test ./...

# Run integration tests with Docker Compose
docker-compose -f docker/docker-compose.test.yml up -d
go test -tags=integration ./...
docker-compose -f docker/docker-compose.test.yml down

# Run benchmarks
go test -bench=. -benchmem ./...

See testing.md for detailed testing guide and manual container setup.

Contributing

Contributions are welcome! Please see our Contributing Guide for details.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Build added in v0.2.0

func Build(opts ...Option) (*logger, error)

Build creates a new logger with the specified options. Returns an error if any option fails during configuration.

func New

func New(opts ...Option) *logger

New creates a new logger with the specified options. If any option returns an error during configuration, New will panic. Use Build() for non-panicking initialization.

func NewLogrLogger

func NewLogrLogger(options ...Option) logr.Logger

NewLogrLogger creates a new logr.Logger backed by mtlog

func NewSlogLogger

func NewSlogLogger(options ...Option) *slog.Logger

NewSlogLogger creates a new slog.Logger backed by mtlog

func WithControlledLevel

func WithControlledLevel(initialLevel core.LogEventLevel) (Option, *LoggingLevelSwitch)

WithControlledLevel creates a level switch and applies it to the logger. Returns both the option and the level switch for external control.

func WithSeqLevelControl

func WithSeqLevelControl(serverURL string, options SeqLevelControllerOptions, seqOptions ...sinks.SeqOption) (Option, *LoggingLevelSwitch, *SeqLevelController)

WithSeqLevelControl creates a logger with Seq-controlled dynamic level adjustment. This convenience function sets up both a Seq sink and automatic level control.

Types

type LogBuilder

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

LogBuilder provides a fluent API for building typed log entries

func (*LogBuilder) Level

func (b *LogBuilder) Level(level core.LogEventLevel) *LogBuilder

Level sets the log level

func (*LogBuilder) Message

func (b *LogBuilder) Message(template string) *LogBuilder

Message sets the message template

func (*LogBuilder) Property

func (b *LogBuilder) Property(name string, value interface{}) *LogBuilder

Property adds a property

func (*LogBuilder) PropertyTyped

func (b *LogBuilder) PropertyTyped(name string, value interface{}) *LogBuilder

PropertyTyped adds a typed property

func (*LogBuilder) Write

func (b *LogBuilder) Write()

Write writes the log entry

type LoggerG

type LoggerG[T any] interface {
	// Logging methods with type safety
	VerboseT(messageTemplate string, value T, args ...interface{})
	DebugT(messageTemplate string, value T, args ...interface{})
	InformationT(messageTemplate string, value T, args ...interface{})
	WarningT(messageTemplate string, value T, args ...interface{})
	ErrorT(messageTemplate string, value T, args ...interface{})
	FatalT(messageTemplate string, value T, args ...interface{})

	// Short method names
	InfoT(messageTemplate string, value T, args ...interface{})
	WarnT(messageTemplate string, value T, args ...interface{})

	// ForContextT adds a typed property
	ForContextT(propertyName string, value T) LoggerG[T]
}

LoggerG is a generic type-safe logger interface

func NewTyped

func NewTyped[T any](opts ...Option) LoggerG[T]

NewTyped creates a new typed logger

type LoggingLevelSwitch

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

LoggingLevelSwitch provides thread-safe, runtime control of the minimum log level. It enables dynamic adjustment of logging levels without restarting the application.

func NewLoggingLevelSwitch

func NewLoggingLevelSwitch(initialLevel core.LogEventLevel) *LoggingLevelSwitch

NewLoggingLevelSwitch creates a new logging level switch with the specified initial level.

func (*LoggingLevelSwitch) Debug

Debug sets the minimum level to Debug.

func (*LoggingLevelSwitch) Error

Error sets the minimum level to Error.

func (*LoggingLevelSwitch) Fatal

Fatal sets the minimum level to Fatal.

func (*LoggingLevelSwitch) Information

func (ls *LoggingLevelSwitch) Information() *LoggingLevelSwitch

Information sets the minimum level to Information.

func (*LoggingLevelSwitch) IsEnabled

func (ls *LoggingLevelSwitch) IsEnabled(level core.LogEventLevel) bool

IsEnabled returns true if the specified level would be processed with the current minimum level setting.

func (*LoggingLevelSwitch) Level

Level returns the current minimum log level.

func (*LoggingLevelSwitch) SetLevel

func (ls *LoggingLevelSwitch) SetLevel(level core.LogEventLevel)

SetLevel updates the minimum log level. This operation is thread-safe and takes effect immediately.

func (*LoggingLevelSwitch) Verbose

func (ls *LoggingLevelSwitch) Verbose() *LoggingLevelSwitch

Verbose sets the minimum level to Verbose.

func (*LoggingLevelSwitch) Warning

func (ls *LoggingLevelSwitch) Warning() *LoggingLevelSwitch

Warning sets the minimum level to Warning.

type Option

type Option func(*config)

Option is a functional option for configuring a logger.

func Debug

func Debug() Option

Debug sets the minimum level to Debug.

func Error

func Error() Option

Error sets the minimum level to Error.

func Information

func Information() Option

Information sets the minimum level to Information.

func Verbose

func Verbose() Option

Verbose sets the minimum level to Verbose.

func Warning

func Warning() Option

Warning sets the minimum level to Warning.

func WithAutoSourceContext added in v0.2.0

func WithAutoSourceContext() Option

WithAutoSourceContext adds automatic source context detection.

func WithCallers

func WithCallers(skip int) Option

WithCallers adds caller information enrichment.

func WithCallersInfo

func WithCallersInfo() Option

WithCallersInfo adds caller information enrichment with default skip.

func WithCommonEnvironment

func WithCommonEnvironment() Option

WithCommonEnvironment adds enrichers for common environment variables.

func WithConsole

func WithConsole() Option

WithConsole adds a console sink.

func WithConsoleProperties

func WithConsoleProperties() Option

WithConsoleProperties adds a console sink that displays properties.

func WithConsoleTemplate added in v0.2.0

func WithConsoleTemplate(template string) Option

WithConsoleTemplate adds a console sink with a custom output template.

func WithConsoleTheme added in v0.2.0

func WithConsoleTheme(theme *sinks.ConsoleTheme) Option

WithConsoleTheme adds a console sink with a custom theme.

func WithCorrelationId

func WithCorrelationId(correlationId string) Option

WithCorrelationId adds a fixed correlation ID to all log events.

func WithCustomDestructuring

func WithCustomDestructuring(maxDepth, maxStringLength, maxCollectionCount int) Option

WithCustomDestructuring adds a destructurer with custom limits.

func WithDestructurer

func WithDestructurer(destructurer core.Destructurer) Option

WithDestructurer sets the destructurer for the pipeline.

func WithDestructuring

func WithDestructuring() Option

WithDestructuring adds the cached destructurer for better performance.

func WithDestructuringDepth

func WithDestructuringDepth(maxDepth int) Option

WithDestructuringDepth adds destructuring with a specific max depth.

func WithDurableBuffer

func WithDurableBuffer(wrapped core.LogEventSink, bufferPath string) Option

WithDurableBuffer adds durable buffering to a sink for reliability.

func WithDurableBufferAdvanced

func WithDurableBufferAdvanced(wrapped core.LogEventSink, options sinks.DurableOptions) Option

WithDurableBufferAdvanced adds durable buffering with advanced options.

func WithDurableElasticsearch

func WithDurableElasticsearch(url, bufferPath string) Option

WithDurableElasticsearch adds an Elasticsearch sink with durable buffering.

func WithDurableSeq

func WithDurableSeq(serverURL, bufferPath string) Option

WithDurableSeq adds a Seq sink with durable buffering.

func WithDurableSplunk

func WithDurableSplunk(url, token, bufferPath string) Option

WithDurableSplunk adds a Splunk sink with durable buffering.

func WithDynamicLevel

func WithDynamicLevel(levelSwitch *LoggingLevelSwitch) Option

WithDynamicLevel enables dynamic level control using a level switch. This is an alias for WithLevelSwitch for better readability.

func WithElasticsearch

func WithElasticsearch(url string) Option

WithElasticsearch adds an Elasticsearch sink with default configuration.

func WithElasticsearchAPIKey

func WithElasticsearchAPIKey(url, apiKey string) Option

WithElasticsearchAPIKey adds an Elasticsearch sink with API key authentication.

func WithElasticsearchAdvanced

func WithElasticsearchAdvanced(url string, opts ...sinks.ElasticsearchOption) Option

WithElasticsearchAdvanced adds an Elasticsearch sink with advanced options.

func WithElasticsearchBasicAuth

func WithElasticsearchBasicAuth(url, username, password string) Option

WithElasticsearchBasicAuth adds an Elasticsearch sink with basic authentication.

func WithEnricher

func WithEnricher(enricher core.LogEventEnricher) Option

WithEnricher adds an enricher to the pipeline.

func WithEnvironment

func WithEnvironment(variableName, propertyName string) Option

WithEnvironment adds environment variable enrichment.

func WithEnvironmentVariables

func WithEnvironmentVariables(variables ...string) Option

WithEnvironmentVariables adds enrichers for multiple environment variables.

func WithExcludeFilter

func WithExcludeFilter(predicate func(*core.LogEvent) bool) Option

WithExcludeFilter adds a filter that excludes events matching the predicate.

func WithFile

func WithFile(path string) Option

WithFile adds a file sink.

func WithFileTemplate added in v0.2.0

func WithFileTemplate(path string, template string) Option

WithFileTemplate adds a file sink with a custom output template.

func WithFilter

func WithFilter(filter core.LogEventFilter) Option

WithFilter adds a filter to the pipeline.

func WithHashSampling

func WithHashSampling(propertyName string, rate float32) Option

WithHashSampling adds a hash-based sampling filter.

func WithLevelFilter

func WithLevelFilter(minimumLevel core.LogEventLevel) Option

WithLevelFilter adds a minimum level filter.

func WithLevelSwitch

func WithLevelSwitch(levelSwitch *LoggingLevelSwitch) Option

WithLevelSwitch enables dynamic level control using the specified level switch. When a level switch is provided, it takes precedence over the static minimum level.

func WithMachineName

func WithMachineName() Option

WithMachineName adds machine name enrichment.

func WithMinimumLevel

func WithMinimumLevel(level core.LogEventLevel) Option

WithMinimumLevel sets the minimum log level.

func WithMinimumLevelOverrides added in v0.2.0

func WithMinimumLevelOverrides(defaultLevel core.LogEventLevel, overrides map[string]core.LogEventLevel) Option

WithMinimumLevelOverrides adds source context-based level filtering.

func WithProcess

func WithProcess() Option

WithProcess adds process information enrichment.

func WithProcessInfo

func WithProcessInfo() Option

WithProcessInfo is an alias for WithProcess.

func WithProperties

func WithProperties(properties map[string]interface{}) Option

WithProperties adds multiple global properties.

func WithProperty

func WithProperty(name string, value interface{}) Option

WithProperty adds a global property to all log events.

func WithPropertyFilter

func WithPropertyFilter(propertyName string, expectedValue interface{}) Option

WithPropertyFilter adds a filter that matches a specific property value.

func WithRateLimit

func WithRateLimit(maxEvents int, windowNanos int64) Option

WithRateLimit adds a rate limiting filter.

func WithSampling

func WithSampling(rate float32) Option

WithSampling adds a sampling filter.

func WithSeq

func WithSeq(serverURL string) Option

WithSeq adds a Seq sink with default configuration.

func WithSeqAPIKey

func WithSeqAPIKey(serverURL, apiKey string) Option

WithSeqAPIKey adds a Seq sink with API key authentication.

func WithSeqAdvanced

func WithSeqAdvanced(serverURL string, opts ...sinks.SeqOption) Option

WithSeqAdvanced adds a Seq sink with advanced options.

func WithSink

func WithSink(sink core.LogEventSink) Option

WithSink adds a sink to the pipeline.

func WithSourceContext added in v0.2.0

func WithSourceContext(sourceContext string) Option

WithSourceContext adds source context enrichment with the specified context.

func WithSplunk

func WithSplunk(url, token string) Option

WithSplunk adds a Splunk sink to the logger.

func WithSplunkAdvanced

func WithSplunkAdvanced(url, token string, opts ...sinks.SplunkOption) Option

WithSplunkAdvanced adds a Splunk sink with advanced options.

func WithThreadId

func WithThreadId() Option

WithThreadId adds goroutine ID enrichment.

func WithTimestamp

func WithTimestamp() Option

WithTimestamp adds timestamp enrichment.

type SeqLevelController

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

SeqLevelController automatically updates a LoggingLevelSwitch based on the minimum level configured in Seq. This enables centralized level control where Seq acts as the source of truth for log levels.

func NewSeqLevelController

func NewSeqLevelController(levelSwitch *LoggingLevelSwitch, seqSink *sinks.SeqSink, options SeqLevelControllerOptions) *SeqLevelController

NewSeqLevelController creates a new controller that synchronizes a level switch with Seq's minimum level setting. The controller will periodically query Seq and update the level switch when changes are detected.

func (*SeqLevelController) Close

func (slc *SeqLevelController) Close()

Close stops the level controller and waits for background operations to complete.

func (*SeqLevelController) ForceCheck

func (slc *SeqLevelController) ForceCheck() error

ForceCheck immediately queries Seq for the current level and updates the level switch if necessary. This is useful for testing or immediate synchronization.

func (*SeqLevelController) GetCurrentLevel

func (slc *SeqLevelController) GetCurrentLevel() core.LogEventLevel

GetCurrentLevel returns the current level from the level switch.

func (*SeqLevelController) GetLastSeqLevel

func (slc *SeqLevelController) GetLastSeqLevel() core.LogEventLevel

GetLastSeqLevel returns the last level retrieved from Seq.

type SeqLevelControllerBuilder

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

SeqLevelControllerBuilder provides a fluent interface for building Seq level controllers.

func NewSeqLevelControllerBuilder

func NewSeqLevelControllerBuilder(serverURL string) *SeqLevelControllerBuilder

NewSeqLevelControllerBuilder creates a new builder for Seq level controllers.

func (*SeqLevelControllerBuilder) Build

Build creates the Seq level controller and returns the logger option, level switch, and controller.

func (*SeqLevelControllerBuilder) WithCheckInterval

func (b *SeqLevelControllerBuilder) WithCheckInterval(interval time.Duration) *SeqLevelControllerBuilder

WithCheckInterval sets the interval for querying Seq.

func (*SeqLevelControllerBuilder) WithErrorHandler

func (b *SeqLevelControllerBuilder) WithErrorHandler(onError func(error)) *SeqLevelControllerBuilder

WithErrorHandler sets the error handler for level checking failures.

func (*SeqLevelControllerBuilder) WithInitialCheck

func (b *SeqLevelControllerBuilder) WithInitialCheck(initialCheck bool) *SeqLevelControllerBuilder

WithInitialCheck controls whether to perform an initial level check.

func (*SeqLevelControllerBuilder) WithLevelSwitch

WithLevelSwitch uses an existing level switch instead of creating a new one.

func (*SeqLevelControllerBuilder) WithSeqAPIKey

WithSeqAPIKey adds API key authentication for Seq.

type SeqLevelControllerOptions

type SeqLevelControllerOptions struct {
	// CheckInterval is how often to query Seq for level changes.
	// Default: 30 seconds
	CheckInterval time.Duration

	// OnError is called when an error occurs during level checking.
	// Default: no-op
	OnError func(error)

	// InitialCheck determines whether to perform an initial check immediately.
	// Default: true
	InitialCheck bool
}

SeqLevelControllerOptions configures a Seq level controller.

type StructuredLogger

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

StructuredLogger provides type-safe structured logging

func NewStructured

func NewStructured(opts ...Option) *StructuredLogger

NewStructured creates a new structured logger

func (*StructuredLogger) Log

func (sl *StructuredLogger) Log(level core.LogEventLevel, messageTemplate string, properties *core.PropertyBag)

Log logs with a typed property bag

func (*StructuredLogger) LogWith

func (sl *StructuredLogger) LogWith() *LogBuilder

LogWith logs with typed properties using a builder pattern

type TypedLogger

type TypedLogger[T any] struct {
	// contains filtered or unexported fields
}

TypedLogger wraps a regular logger with type-safe methods

func (*TypedLogger[T]) DebugT

func (l *TypedLogger[T]) DebugT(messageTemplate string, value T, args ...interface{})

DebugT logs at debug level with typed value

func (*TypedLogger[T]) ErrorT

func (l *TypedLogger[T]) ErrorT(messageTemplate string, value T, args ...interface{})

ErrorT logs at error level with typed value

func (*TypedLogger[T]) FatalT

func (l *TypedLogger[T]) FatalT(messageTemplate string, value T, args ...interface{})

FatalT logs at fatal level with typed value

func (*TypedLogger[T]) ForContextT

func (l *TypedLogger[T]) ForContextT(propertyName string, value T) LoggerG[T]

ForContextT adds a typed property to the logger context

func (*TypedLogger[T]) InfoT

func (l *TypedLogger[T]) InfoT(messageTemplate string, value T, args ...interface{})

InfoT writes an information-level log event with a typed value (alias for InformationT)

func (*TypedLogger[T]) InformationT

func (l *TypedLogger[T]) InformationT(messageTemplate string, value T, args ...interface{})

InformationT logs at information level with typed value

func (*TypedLogger[T]) VerboseT

func (l *TypedLogger[T]) VerboseT(messageTemplate string, value T, args ...interface{})

VerboseT logs at verbose level with typed value

func (*TypedLogger[T]) WarnT

func (l *TypedLogger[T]) WarnT(messageTemplate string, value T, args ...interface{})

WarnT writes a warning-level log event with a typed value (alias for WarningT)

func (*TypedLogger[T]) WarningT

func (l *TypedLogger[T]) WarningT(messageTemplate string, value T, args ...interface{})

WarningT logs at warning level with typed value

Directories

Path Synopsis
adapters
otel module
sentry module
cmd
Package core provides the fundamental interfaces and types for mtlog.
Package core provides the fundamental interfaces and types for mtlog.
examples
async command
basic command
configuration command
context command
destructuring command
durable command
dynamic-levels command
elasticsearch command
enrichers command
filtering command
generics command
go-templates command
logvalue command
rolling command
seq command
showcase command
splunk command
themes command
internal

Jump to

Keyboard shortcuts

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