core

package
v0.10.0 Latest Latest
Warning

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

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

Documentation

Overview

Package core provides the fundamental interfaces and types for mtlog.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddTyped

func AddTyped[T any](pb *PropertyBag, name string, value T)

AddTyped adds a typed property to the bag

func GetTyped

func GetTyped[T any](pb *PropertyBag, name string) (T, bool)

GetTyped retrieves a typed property from the bag

Types

type AdaptiveSamplingPolicy added in v0.10.0

type AdaptiveSamplingPolicy interface {
	SamplingPolicy

	// SetTargetRate sets the target events per second.
	SetTargetRate(eventsPerSecond float64)

	// GetCurrentRate returns the current sampling rate.
	GetCurrentRate() float64
}

AdaptiveSamplingPolicy adjusts sampling rate based on load.

type Capturer added in v0.6.0

type Capturer interface {
	// TryCapture attempts to capture a value into a log event property.
	// Returns the property and true if successful, nil and false otherwise.
	TryCapture(value any, propertyFactory LogEventPropertyFactory) (*LogEventProperty, bool)
}

Capturer converts complex types to log-appropriate representations.

type CompositeSamplingPolicy added in v0.10.0

type CompositeSamplingPolicy interface {
	SamplingPolicy

	// Add adds a policy to the composite.
	Add(policy SamplingPolicy)

	// Remove removes a policy from the composite.
	Remove(policy SamplingPolicy)
}

CompositeSamplingPolicy combines multiple policies with AND/OR logic.

type DeadlineStats added in v0.10.0

type DeadlineStats struct {
	CacheSize            int           // Current number of contexts in the deadline cache
	CacheCapacity        int           // Maximum capacity of the deadline cache
	FirstWarningCount    int           // Number of contexts that have received first warnings
	FirstWarningCapacity int           // Maximum capacity of first warning set
	CacheTTL             time.Duration // Time-to-live for cache entries
}

DeadlineStats provides statistics about deadline tracking.

type LogEvent

type LogEvent struct {
	// Timestamp is when the event occurred.
	Timestamp time.Time

	// Level is the severity of the event.
	Level LogEventLevel

	// MessageTemplate is the original message template with placeholders.
	MessageTemplate string

	// Properties contains the event's properties extracted from the template.
	Properties map[string]any

	// Exception associated with the event, if any.
	Exception error
}

LogEvent represents a single log event with all its properties.

func (*LogEvent) AddProperty

func (e *LogEvent) AddProperty(name string, value any)

AddProperty adds or overwrites a property in the event.

func (*LogEvent) AddPropertyIfAbsent

func (e *LogEvent) AddPropertyIfAbsent(property *LogEventProperty)

AddPropertyIfAbsent adds a property to the event if it doesn't already exist.

func (*LogEvent) RenderMessage added in v0.10.0

func (e *LogEvent) RenderMessage() string

RenderMessage renders the message template with the event's properties. This method parses the MessageTemplate and replaces all placeholders with their corresponding property values, handling format specifiers, capturing operators, and scalar hints.

If parsing fails, the original MessageTemplate is returned as a fallback.

Example:

event := &LogEvent{
    MessageTemplate: "User {UserId} logged in from {City}",
    Properties: map[string]any{
        "UserId": 123,
        "City": "Seattle",
    },
}
message := event.RenderMessage()  // "User 123 logged in from Seattle"

type LogEventEnricher

type LogEventEnricher interface {
	// Enrich adds properties to the provided log event.
	Enrich(event *LogEvent, propertyFactory LogEventPropertyFactory)
}

LogEventEnricher adds contextual properties to log events.

type LogEventFilter

type LogEventFilter interface {
	// IsEnabled returns true if the event should be logged.
	IsEnabled(event *LogEvent) bool
}

LogEventFilter determines which events proceed through the pipeline.

type LogEventLevel

type LogEventLevel int

LogEventLevel specifies the severity of a log event.

const (
	// VerboseLevel is the most detailed logging level.
	VerboseLevel LogEventLevel = iota

	// DebugLevel is for debugging information.
	DebugLevel

	// InformationLevel is for informational messages.
	InformationLevel

	// WarningLevel is for warnings.
	WarningLevel

	// ErrorLevel is for errors.
	ErrorLevel

	// FatalLevel is for fatal errors.
	FatalLevel
)

type LogEventProperty

type LogEventProperty struct {
	// Name is the property name.
	Name string

	// Value is the property value.
	Value any
}

LogEventProperty represents a single property of a log event.

type LogEventPropertyFactory

type LogEventPropertyFactory interface {
	// CreateProperty creates a new log event property.
	CreateProperty(name string, value any) *LogEventProperty
}

LogEventPropertyFactory creates log event properties.

type LogEventSink

type LogEventSink interface {
	// Emit writes the log event to the sink's destination.
	Emit(event *LogEvent)

	// Close releases any resources held by the sink.
	Close() error
}

LogEventSink outputs log events to a destination.

type LogValue

type LogValue interface {
	// LogValue returns the value to be logged. This can be a simple type
	// (string, number, bool) or a complex type (struct, map, slice).
	// The returned value may itself be captured if it's complex.
	LogValue() any
}

LogValue is an optional interface that types can implement to provide custom log representations. When a type implements this interface, the capturer will use the returned value instead of using reflection.

type Logger

type Logger interface {
	// Verbose writes a verbose-level log event.
	Verbose(messageTemplate string, args ...any)

	// Debug writes a debug-level log event.
	Debug(messageTemplate string, args ...any)

	// Information writes an information-level log event.
	Information(messageTemplate string, args ...any)

	// Warning writes a warning-level log event.
	Warning(messageTemplate string, args ...any)

	// Error writes an error-level log event.
	Error(messageTemplate string, args ...any)

	// Fatal writes a fatal-level log event.
	Fatal(messageTemplate string, args ...any)

	// Write writes a log event at the specified level.
	Write(level LogEventLevel, messageTemplate string, args ...any)

	// ForContext creates a logger that enriches events with the specified property.
	ForContext(propertyName string, value any) Logger

	// WithContext creates a logger that enriches events with context values.
	WithContext(ctx context.Context) Logger

	// With creates a logger that enriches events with the specified key-value pairs.
	// Keys must be strings. Values can be any type.
	// The key-value pairs should be provided in the order: key1, value1, key2, value2, ...
	// If an odd number of arguments is provided, the last argument is ignored.
	With(args ...any) Logger

	// IsEnabled returns true if events at the specified level would be processed.
	IsEnabled(level LogEventLevel) bool

	// Info writes an information-level log event (alias for Information).
	Info(messageTemplate string, args ...any)

	// Warn writes a warning-level log event (alias for Warning).
	Warn(messageTemplate string, args ...any)

	// VerboseContext writes a verbose-level log event with context awareness.
	VerboseContext(ctx context.Context, messageTemplate string, args ...any)

	// DebugContext writes a debug-level log event with context awareness.
	DebugContext(ctx context.Context, messageTemplate string, args ...any)

	// InfoContext writes an information-level log event with context awareness.
	InfoContext(ctx context.Context, messageTemplate string, args ...any)

	// WarnContext writes a warning-level log event with context awareness.
	WarnContext(ctx context.Context, messageTemplate string, args ...any)

	// ErrorContext writes an error-level log event with context awareness.
	ErrorContext(ctx context.Context, messageTemplate string, args ...any)

	// FatalContext writes a fatal-level log event with context awareness.
	FatalContext(ctx context.Context, messageTemplate string, args ...any)

	// Sample creates a logger that samples every nth message.
	Sample(n uint64) Logger

	// SampleDuration creates a logger that samples at most once per duration.
	SampleDuration(duration time.Duration) Logger

	// SampleRate creates a logger that samples a percentage of messages (0.0 to 1.0).
	SampleRate(rate float32) Logger

	// SampleFirst creates a logger that logs only the first n occurrences.
	SampleFirst(n uint64) Logger

	// SampleGroup creates a logger that samples messages within a named group.
	SampleGroup(groupName string, n uint64) Logger

	// SampleWhen creates a logger that samples conditionally based on a predicate.
	SampleWhen(predicate func() bool, n uint64) Logger

	// SampleBackoff creates a logger that samples with exponential backoff.
	SampleBackoff(key string, factor float64) Logger

	// ResetSampling resets all sampling counters for this logger.
	ResetSampling()

	// ResetSamplingGroup resets the sampling counter for a specific group.
	ResetSamplingGroup(groupName string)

	// EnableSamplingSummary enables periodic emission of sampling summary events.
	EnableSamplingSummary(period time.Duration) Logger

	// GetSamplingStats returns current sampling statistics.
	GetSamplingStats() (sampled uint64, skipped uint64)

	// SampleProfile applies a predefined sampling profile optimized for common scenarios.
	SampleProfile(profileName string) Logger

	// SampleAdaptive creates a logger that adjusts sampling rates based on target events per second.
	SampleAdaptive(targetEventsPerSecond uint64) Logger

	// SampleAdaptiveWithOptions creates a logger with adaptive sampling and custom parameters.
	SampleAdaptiveWithOptions(targetEventsPerSecond uint64, minRate, maxRate float64, adjustmentInterval time.Duration) Logger

	// DeadlineStats returns deadline tracking statistics if deadline awareness is enabled.
	// Returns nil if deadline awareness is not configured.
	DeadlineStats() interface{}

	// WithDeadlineWarning creates a logger with modified deadline warning threshold.
	// This allows creating derived loggers with different deadline configurations.
	WithDeadlineWarning(threshold time.Duration, opts ...interface{}) Logger
}

Logger is the main logging interface providing structured logging methods.

type PropertyBag

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

PropertyBag is a type-safe property collection

func NewPropertyBag

func NewPropertyBag() *PropertyBag

NewPropertyBag creates a new property bag

func (*PropertyBag) Add

func (pb *PropertyBag) Add(name string, value any)

Add adds a typed property to the bag

func (*PropertyBag) Get

func (pb *PropertyBag) Get(name string) (any, bool)

Get retrieves a property from the bag

func (*PropertyBag) Properties

func (pb *PropertyBag) Properties() map[string]any

Properties returns all properties as a map

type PropertyValue

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

PropertyValue represents a typed property value using generics

func NewPropertyValue

func NewPropertyValue[T any](value T) PropertyValue[T]

NewPropertyValue creates a new typed property value

func (PropertyValue[T]) ToLogEventProperty

func (p PropertyValue[T]) ToLogEventProperty(name string, factory LogEventPropertyFactory) *LogEventProperty

ToLogEventProperty converts to a LogEventProperty

func (PropertyValue[T]) Value

func (p PropertyValue[T]) Value() T

Value returns the underlying value

type SamplingMetrics added in v0.10.0

type SamplingMetrics struct {
	// Group sampling cache metrics
	GroupCacheHits      uint64 // Number of cache hits for group sampling
	GroupCacheMisses    uint64 // Number of cache misses for group sampling
	GroupCacheSize      int    // Current size of group cache
	GroupCacheEvictions uint64 // Number of evictions from group cache

	// Backoff sampling cache metrics
	BackoffCacheHits      uint64 // Number of cache hits for backoff sampling
	BackoffCacheMisses    uint64 // Number of cache misses for backoff sampling
	BackoffCacheSize      int    // Current size of backoff cache
	BackoffCacheEvictions uint64 // Number of evictions from backoff cache

	// Adaptive sampling metrics
	AdaptiveCacheHits   uint64 // Number of cache hits for adaptive sampling
	AdaptiveCacheMisses uint64 // Number of cache misses for adaptive sampling
	AdaptiveCacheSize   int    // Current size of adaptive cache

	// Overall sampling decisions
	TotalSampled uint64 // Total events sampled across all strategies
	TotalSkipped uint64 // Total events skipped across all strategies
}

SamplingMetrics provides detailed metrics about sampling cache performance. This helps operators tune cache limits and understand sampling behavior.

func (SamplingMetrics) Format added in v0.10.0

func (m SamplingMetrics) Format(f fmt.State, verb rune)

Format implements fmt.Formatter for custom formatting options. Supports:

%s - Default string representation
%v - Same as %s
%+v - Verbose format with field names
%#v - Go syntax representation

func (SamplingMetrics) PrometheusMetrics added in v0.10.0

func (m SamplingMetrics) PrometheusMetrics() map[string]float64

PrometheusMetrics returns sampling metrics as a map suitable for Prometheus export. This makes it easy to integrate with monitoring systems.

func (SamplingMetrics) String added in v0.10.0

func (m SamplingMetrics) String() string

String returns a human-readable summary of sampling metrics. This is useful for periodic logging of sampling performance.

type SamplingPolicy added in v0.10.0

type SamplingPolicy interface {
	// ShouldSample determines if an event should be logged.
	ShouldSample(event *LogEvent) bool

	// Reset resets any internal state of the sampling policy.
	Reset()

	// Stats returns current sampling statistics.
	Stats() SamplingStats
}

SamplingPolicy defines the interface for custom sampling strategies. Implementations should be thread-safe as they may be called concurrently.

type SamplingPolicyFunc added in v0.10.0

type SamplingPolicyFunc func(event *LogEvent) bool

SamplingPolicyFunc is a function adapter for SamplingPolicy.

func (SamplingPolicyFunc) Reset added in v0.10.0

func (f SamplingPolicyFunc) Reset()

Reset is a no-op for function-based policies.

func (SamplingPolicyFunc) ShouldSample added in v0.10.0

func (f SamplingPolicyFunc) ShouldSample(event *LogEvent) bool

ShouldSample calls the function.

func (SamplingPolicyFunc) Stats added in v0.10.0

Stats returns zero stats for function-based policies.

type SamplingStats added in v0.10.0

type SamplingStats struct {
	Sampled uint64 // Number of events that were sampled (logged)
	Skipped uint64 // Number of events that were skipped
}

SamplingStats contains statistics about sampling decisions.

type SimpleSink

type SimpleSink interface {
	LogEventSink

	// EmitSimple writes a simple log message without allocations.
	EmitSimple(timestamp time.Time, level LogEventLevel, message string)
}

SimpleSink is an optional interface for sinks that support zero-allocation simple logging.

type TimeBasedSamplingPolicy added in v0.10.0

type TimeBasedSamplingPolicy interface {
	SamplingPolicy

	// SetWindow sets the time window for sampling.
	SetWindow(duration time.Duration)

	// GetWindow returns the current time window.
	GetWindow() time.Duration
}

TimeBasedSamplingPolicy samples events based on time windows.

Jump to

Keyboard shortcuts

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