log

package
v0.0.1-dev.12 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2025 License: MIT Imports: 12 Imported by: 0

README

Rune Logging System

The Rune logging system provides a comprehensive, structured logging framework for all components of the Rune orchestration platform. It supports multiple log levels, structured data, context propagation, and various output formats and destinations.

Key Features

  • Structured Logging: Log entries include structured data as key-value pairs
  • Type-Safe Field API: Strongly-typed field helpers for better developer experience
  • Multiple Log Levels: DEBUG, INFO, WARN, ERROR, FATAL
  • Context Propagation: Trace request flows across distributed components
  • Multiple Output Formats: JSON, text with colored formatting
  • Multiple Output Destinations: Console, files (with rotation), extensible for others
  • Performance Optimized: Minimal overhead with support for sampling high-volume logs
  • Security Features: Redaction of sensitive fields
  • Distributed Tracing: OpenTelemetry compatibility (placeholder)
import "github.com/razorbill/rune/pkg/log"

// Simple logging with fields
log.Info("Server starting", log.Int("port", 8080))

// Multiple fields with type safety
log.Info("Request completed",
    log.Component("http-server"),
    log.Int("status", 200),
    log.Str("method", "GET"),
    log.Str("path", "/users"),
    log.Duration("latency_ms", time.Since(start)))

// Error logging with contextual information
if err := someOperation(); err != nil {
    log.Error("Operation failed", 
        log.Err(err),
        log.Str("operation", "someOperation"),
        log.Component("processor"))
}

Component-Specific Loggers

Create loggers specific to components for better filtering and organization:

// Create a component-specific logger
apiLogger := log.With(log.Component("api-server"))

// Use the component logger
apiLogger.Info("API server starting")
apiLogger.Info("Route registered", log.Str("path", "/users"))

Request Context Propagation

Trace requests across components with context propagation:

// In HTTP handler middleware
func LoggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Generate or extract request ID
        reqID := r.Header.Get("X-Request-ID")
        if reqID == "" {
            reqID = uuid.New().String()
        }
        
        // Add request ID to context
        ctx := context.WithValue(r.Context(), log.RequestIDKey, reqID)
        
        // Add logger with request ID to context
        requestLogger := log.With(log.RequestID(reqID))
        ctx = log.WithLogger(ctx, requestLogger)
        
        // Log incoming request
        requestLogger.Info("Request started",
            log.Str("method", r.Method),
            log.Str("path", r.URL.Path),
            log.Str("remote_addr", r.RemoteAddr))
        
        start := time.Now()
        
        // Call next handler with updated context
        next.ServeHTTP(w, r.WithContext(ctx))
        
        // Log completion with duration
        requestLogger.Info("Request completed",
            log.Int("status", getStatusCode(w)),
            log.Duration("duration_ms", time.Since(start)))
    })
}

// In another component that receives the context
func ProcessRequest(ctx context.Context) {
    // Get logger from context with all the request tracking fields
    logger := log.FromContext(ctx)
    
    logger.Info("Processing request")
    // ... processing logic ...
    logger.Info("Request processed successfully", 
        log.Int("items_processed", 42))
}

Available Field Types

The logging system provides type-safe field constructors:

log.Str("key", "value")      // String field
log.Int("key", 123)          // Integer field
log.Int64("key", 123)        // Int64 field
log.Float64("key", 123.45)   // Float64 field
log.Bool("key", true)        // Boolean field
log.Err(err)                 // Error field
log.Time("key", time.Now())  // Time field
log.Duration("key", duration) // Duration field
log.Any("key", value)        // Any value type
log.F("key", value)          // Generic field (alias for Any)

// Context-specific field helpers
log.Component("component-name")  // Component identifier
log.RequestID("req-id")          // Request ID
log.TraceID("trace-id")          // Trace ID
log.SpanID("span-id")            // Span ID

Configuration

Configure logging via code:

logger := log.NewLogger(
    log.WithLevel(log.InfoLevel),
    log.WithFormatter(&log.TextFormatter{
        FullTimestamp: true,
        DisableColors: false,
    }),
    log.WithOutput(log.NewFileOutput("/var/log/rune/service.log", 
        log.WithMaxSize(100*1024*1024), // 100MB
        log.WithMaxBackups(5),
    )),
)

// Set as default logger
log.SetDefaultLogger(logger)

Or via configuration:

config := &log.Config{
    Level:  "info",
    Format: "json",
    Outputs: []log.OutputConfig{
        {
            Type: "file",
            Options: map[string]interface{}{
                "filename":    "/var/log/rune/service.log",
                "max_size":    "100MB",
                "max_backups": 5,
            },
        },
        {
            Type: "console",
            Options: map[string]interface{}{
                "error_to_stderr": true,
            },
        },
    },
    RedactedFields: []string{"password", "api_key", "token"},
}

logger, err := log.ApplyConfig(config)
if err != nil {
    panic(err)
}

log.SetDefaultLogger(logger)

The original key-value pair API is still supported for backward compatibility:

// These methods use the "f" suffix to indicate they use the older format
log.Infof("Server starting", "port", 8080)
log.Errorf("Operation failed", "error", err.Error(), "operation", "someOperation")

// WithField/WithFields for the older API
logger := log.WithField("component", "api-server")
logger.Infof("Server starting")

Performance Considerations

  • Use appropriate log levels (DEBUG for development, INFO or higher for production)
  • Consider sampling for high-volume logs
  • Use structured fields consistently for easier parsing and querying
  • Close file outputs properly when the application exits

Best Practices

  1. Use the Field API: The Field-based API provides better type safety and IDE support
  2. Tag with Component: Always tag logs with a component name using log.Component()
  3. Propagate Context: Always propagate request context with IDs
  4. Add Context to Errors: Always add context to error logs with log.Err(err)
  5. Use Semantic Field Names: Use consistent, semantic field names
  6. Security: Use RedactedFields for sensitive data
  7. Resource Cleanup: Close file outputs properly

Documentation

Overview

Package log provides a structured logging system for Rune services.

Index

Constants

View Source
const (
	RequestIDKey = "request_id"
	TraceIDKey   = "trace_id"
	SpanIDKey    = "span_id"
	ComponentKey = "component"
	OperationKey = "operation"
)

Context keys for propagating logging context

Variables

View Source
var ErrEntrySampled = &entrySampledError{}

ErrEntrySampled is returned when an entry is sampled out.

Functions

func ContextInjector

func ContextInjector(ctx context.Context, fields Fields) context.Context

ContextInjector injects logging fields into a context.Context.

func Debug

func Debug(msg string, fields ...Field)

Standard global logging methods with fields

func Debugf

func Debugf(msg string, args ...interface{})

Standard global logging methods with key-value pairs (for backward compatibility)

func Error

func Error(msg string, fields ...Field)

func Errorf

func Errorf(msg string, args ...interface{})

func Fatal

func Fatal(msg string, fields ...Field)

func Fatalf

func Fatalf(msg string, args ...interface{})

func Info

func Info(msg string, fields ...Field)

func Infof

func Infof(msg string, args ...interface{})

func RedirectStdLog

func RedirectStdLog(logger Logger) func()

RedirectStdLog redirects the standard library's default logger to our logger This is useful for capturing logs from third-party libraries that use the standard log package directly

func SetDefaultLogger

func SetDefaultLogger(logger Logger)

SetDefaultLogger sets the global default logger.

func StdLogWriter

func StdLogWriter(logger Logger, level Level) io.Writer

StdLogWriter creates an io.Writer that logs lines at the specified level Useful for redirecting output from third-party libraries

func ToStdLogger

func ToStdLogger(logger Logger, prefix string, flag int) *stdlog.Logger

ToStdLogger converts our structured Logger to a standard library *log.Logger This is helpful for integrating with libraries or components that expect a standard logger

func Warn

func Warn(msg string, fields ...Field)

func Warnf

func Warnf(msg string, args ...interface{})

func WithLogger

func WithLogger(ctx context.Context, logger Logger) context.Context

WithLogger adds a logger to a context.Context.

Types

type BaseLogger

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

BaseLogger implements the Logger interface.

func (*BaseLogger) Debug

func (l *BaseLogger) Debug(msg string, fields ...Field)

Debug logs a message at the debug level with fields.

func (*BaseLogger) Debugf

func (l *BaseLogger) Debugf(msg string, args ...interface{})

Debugf logs a message at the debug level with key-value args.

func (*BaseLogger) Error

func (l *BaseLogger) Error(msg string, fields ...Field)

Error logs a message at the error level with fields.

func (*BaseLogger) Errorf

func (l *BaseLogger) Errorf(msg string, args ...interface{})

Errorf logs a message at the error level with key-value args.

func (*BaseLogger) Fatal

func (l *BaseLogger) Fatal(msg string, fields ...Field)

Fatal logs a message at the fatal level with fields and then exits.

func (*BaseLogger) Fatalf

func (l *BaseLogger) Fatalf(msg string, args ...interface{})

Fatalf logs a message at the fatal level with key-value args and then exits.

func (*BaseLogger) GetLevel

func (l *BaseLogger) GetLevel() Level

GetLevel returns the current minimum log level.

func (*BaseLogger) Info

func (l *BaseLogger) Info(msg string, fields ...Field)

Info logs a message at the info level with fields.

func (*BaseLogger) Infof

func (l *BaseLogger) Infof(msg string, args ...interface{})

Infof logs a message at the info level with key-value args.

func (*BaseLogger) Outputs

func (l *BaseLogger) Outputs() []Output

Outputs returns the configured log outputs.

func (*BaseLogger) SetLevel

func (l *BaseLogger) SetLevel(level Level)

SetLevel sets the minimum log level.

func (*BaseLogger) Warn

func (l *BaseLogger) Warn(msg string, fields ...Field)

Warn logs a message at the warn level with fields.

func (*BaseLogger) Warnf

func (l *BaseLogger) Warnf(msg string, args ...interface{})

Warnf logs a message at the warn level with key-value args.

func (*BaseLogger) With

func (l *BaseLogger) With(fields ...Field) Logger

With adds fields to the logger (new Field-based API)

func (*BaseLogger) WithComponent

func (l *BaseLogger) WithComponent(component string) Logger

WithComponent returns a new logger with the component field added.

func (*BaseLogger) WithContext

func (l *BaseLogger) WithContext(ctx context.Context) Logger

WithContext returns a new logger with fields from the context.

func (*BaseLogger) WithError

func (l *BaseLogger) WithError(err error) Logger

WithError returns a new logger with the error added as a field.

func (*BaseLogger) WithField

func (l *BaseLogger) WithField(key string, value interface{}) Logger

WithField returns a new logger with the field added to it.

func (*BaseLogger) WithFields

func (l *BaseLogger) WithFields(fields Fields) Logger

WithFields returns a new logger with the fields added to it.

type Config

type Config struct {
	// Level sets the minimum log level
	Level string `json:"level" yaml:"level"`

	// Format sets the output format (json, text)
	Format string `json:"format" yaml:"format"`

	// Outputs defines where logs should be written
	Outputs []OutputConfig `json:"outputs" yaml:"outputs"`

	// Sampling defines sampling behavior for high-volume logs
	Sampling *SamplingConfig `json:"sampling" yaml:"sampling"`

	// EnableCaller enables adding caller information to logs
	EnableCaller bool `json:"enable_caller" yaml:"enable_caller"`

	// RedactedFields lists fields that should be redacted (e.g. passwords)
	RedactedFields []string `json:"redacted_fields" yaml:"redacted_fields"`
}

Config defines logging configuration.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a default configuration.

type ConsoleOutput

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

ConsoleOutput writes log entries to the console (stdout/stderr).

func NewConsoleOutput

func NewConsoleOutput(options ...ConsoleOutputOption) *ConsoleOutput

NewConsoleOutput creates a new ConsoleOutput with the given options.

func (*ConsoleOutput) Close

func (o *ConsoleOutput) Close() error

Close implements the Output interface but does nothing for console output.

func (*ConsoleOutput) Write

func (o *ConsoleOutput) Write(entry *Entry, formattedEntry []byte) error

Write writes the log entry to the console.

type ConsoleOutputOption

type ConsoleOutputOption func(*ConsoleOutput)

ConsoleOutputOption is a function that configures a ConsoleOutput.

func WithCustomErrorWriter

func WithCustomErrorWriter(writer io.Writer) ConsoleOutputOption

WithCustomErrorWriter configures the ConsoleOutput to use a custom error writer.

func WithCustomWriter

func WithCustomWriter(writer io.Writer) ConsoleOutputOption

WithCustomWriter configures the ConsoleOutput to use a custom writer.

func WithErrorToStderr

func WithErrorToStderr() ConsoleOutputOption

WithErrorToStderr configures the ConsoleOutput to send error and fatal logs to stderr.

func WithStderr

func WithStderr() ConsoleOutputOption

WithStderr configures the ConsoleOutput to use stderr.

type Entry

type Entry struct {
	Level     Level
	Message   string
	Fields    Fields
	Timestamp time.Time
	Caller    string
	Error     error
}

Entry represents a single log entry.

type Field

type Field struct {
	Key   string
	Value interface{}
}

Field represents a structured log field with a key and value

func Any

func Any(key string, value interface{}) Field

Any creates a field for any value (alias for F)

func Bool

func Bool(key string, value bool) Field

Bool creates a boolean field

func Component

func Component(value string) Field

Component creates a component field, useful for tagging logs with a component name

func Duration

func Duration(key string, value time.Duration) Field

Duration creates a duration field

func Err

func Err(err error) Field

Err creates an error field

func F

func F(key string, value interface{}) Field

F creates a log field with the provided key and value

func Float64

func Float64(key string, value float64) Field

Float64 creates a float64 field

func Int

func Int(key string, value int) Field

Int creates an integer field

func Int64

func Int64(key string, value int64) Field

Int64 creates an int64 field

func Json

func Json(key string, value interface{}) Field

JSON creates a field for a JSON-serializable value

func RequestID

func RequestID(value string) Field

RequestID creates a request ID field

func SpanID

func SpanID(value string) Field

SpanID creates a span ID field

func Str

func Str(key, value string) Field

Str creates a string field

func Time

func Time(key string, value time.Time) Field

Time creates a time field

func TraceID

func TraceID(value string) Field

TraceID creates a trace ID field

type Fields

type Fields map[string]interface{}

Fields is a map of field names to values.

func ContextExtractor

func ContextExtractor(ctx context.Context) Fields

ContextExtractor extracts logging context from a context.Context.

type FileOutput

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

FileOutput writes log entries to a file.

func NewFileOutput

func NewFileOutput(filename string, options ...FileOutputOption) *FileOutput

NewFileOutput creates a new FileOutput with the given options.

func (*FileOutput) Close

func (o *FileOutput) Close() error

Close closes the file.

func (*FileOutput) Write

func (o *FileOutput) Write(entry *Entry, formattedEntry []byte) error

Write writes the log entry to the file.

type FileOutputOption

type FileOutputOption func(*FileOutput)

FileOutputOption is a function that configures a FileOutput.

func WithBackupFormat

func WithBackupFormat(format string) FileOutputOption

WithBackupFormat sets the format for backup filenames.

func WithMaxAge

func WithMaxAge(maxAge time.Duration) FileOutputOption

WithMaxAge sets the maximum file age.

func WithMaxBackups

func WithMaxBackups(maxBackups int) FileOutputOption

WithMaxBackups sets the maximum number of backup files.

func WithMaxSize

func WithMaxSize(maxBytes int64) FileOutputOption

WithMaxSize sets the maximum file size.

type Formatter

type Formatter interface {
	Format(entry *Entry) ([]byte, error)
}

Formatter defines the interface for formatting log entries.

type Hook

type Hook interface {
	Levels() []Level
	Fire(entry *Entry) error
}

Hook is a function that is called during logging.

type JSONFormatter

type JSONFormatter struct {
	TimestampFormat string // Format for timestamps
	EnableCaller    bool   // Enable caller information (default: false)
}

JSONFormatter formats log entries as JSON.

func (*JSONFormatter) Format

func (f *JSONFormatter) Format(entry *Entry) ([]byte, error)

Format formats the entry as JSON.

type Level

type Level int

Level represents the severity level of a log message.

const (
	DebugLevel Level = iota
	InfoLevel
	WarnLevel
	ErrorLevel
	FatalLevel
)

Log levels

func ParseLevel

func ParseLevel(level string) (Level, error)

ParseLevel parses a level string into a Level.

func (Level) String

func (l Level) String() string

String returns the string representation of the log level.

type Logger

type Logger interface {
	// Standard logging methods with structured context (Field-based API)
	Debug(msg string, fields ...Field)
	Info(msg string, fields ...Field)
	Warn(msg string, fields ...Field)
	Error(msg string, fields ...Field)
	Fatal(msg string, fields ...Field)

	// Standard logging methods with key-value pairs (for backward compatibility)
	Debugf(msg string, args ...interface{})
	Infof(msg string, args ...interface{})
	Warnf(msg string, args ...interface{})
	Errorf(msg string, args ...interface{})
	Fatalf(msg string, args ...interface{})

	// Field creation methods (for backward compatibility)
	WithField(key string, value interface{}) Logger
	WithFields(fields Fields) Logger
	WithError(err error) Logger

	// With adds multiple fields to the logger (for new Field-based API)
	With(fields ...Field) Logger

	// WithContext adds request context to the Logger
	WithContext(ctx context.Context) Logger

	// WithComponent tags logs with a component name
	WithComponent(component string) Logger

	// SetLevel sets the minimum log level
	SetLevel(level Level)

	// GetLevel returns the current minimum log level
	GetLevel() Level
}

Logger defines the core logging interface for Rune components.

func ApplyConfig

func ApplyConfig(config *Config) (Logger, error)

ApplyConfig creates a logger from a configuration.

func FromContext

func FromContext(ctx context.Context) Logger

FromContext extracts a logger from a context.Context. If no logger is found, it returns the default logger.

func GetDefaultLogger

func GetDefaultLogger() Logger

GetDefaultLogger returns the global default logger.

func NewLogger

func NewLogger(options ...LoggerOption) Logger

NewLogger creates a new logger with the given options.

func With

func With(fields ...Field) Logger

With adds fields to the logger (for new Field-based API)

func WithComponent

func WithComponent(component string) Logger

func WithContext

func WithContext(ctx context.Context) Logger

func WithError

func WithError(err error) Logger

func WithField

func WithField(key string, value interface{}) Logger

For backward compatibility

func WithFields

func WithFields(fields Fields) Logger

type LoggerOption

type LoggerOption func(*BaseLogger)

LoggerOption is a function that configures a logger.

func WithFormatter

func WithFormatter(formatter Formatter) LoggerOption

WithFormatter sets the log formatter.

func WithHook

func WithHook(hook Hook) LoggerOption

WithHook adds a hook to the logger.

func WithLevel

func WithLevel(level Level) LoggerOption

WithLevel sets the minimum log level.

func WithOutput

func WithOutput(output Output) LoggerOption

WithOutput adds an output to the logger.

type NullOutput

type NullOutput struct{}

NullOutput discards all log entries.

func NewNullOutput

func NewNullOutput() *NullOutput

NewNullOutput creates a new NullOutput.

func (*NullOutput) Close

func (o *NullOutput) Close() error

Close implements the Output interface but does nothing.

func (*NullOutput) Write

func (o *NullOutput) Write(entry *Entry, formattedEntry []byte) error

Write implements the Output interface but does nothing.

type OTELHook

type OTELHook struct{}

OTELHook integrates with OpenTelemetry to add trace information to logs.

func NewOTELHook

func NewOTELHook() *OTELHook

NewOTELHook creates a new OpenTelemetry hook.

func (*OTELHook) Fire

func (h *OTELHook) Fire(entry *Entry) error

Fire executes the hook's logic for a log entry.

func (*OTELHook) Levels

func (h *OTELHook) Levels() []Level

Levels returns the levels this hook should be called for.

type Output

type Output interface {
	Write(entry *Entry, formattedEntry []byte) error
	Close() error
}

Output defines the interface for log outputs.

type OutputConfig

type OutputConfig struct {
	// Type is the output type (console, file, syslog, remote)
	Type string `json:"type" yaml:"type"`

	// Options are type-specific configuration options
	Options map[string]interface{} `json:"options" yaml:"options"`
}

OutputConfig defines a single log output.

type RedactionHook

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

RedactionHook redacts sensitive values from log entries.

func NewRedactionHook

func NewRedactionHook(fields []string) *RedactionHook

NewRedactionHook creates a new redaction hook.

func (*RedactionHook) Fire

func (h *RedactionHook) Fire(entry *Entry) error

Fire executes the hook's logic for a log entry.

func (*RedactionHook) Levels

func (h *RedactionHook) Levels() []Level

Levels returns the levels this hook should be called for.

type SamplingConfig

type SamplingConfig struct {
	// Initial is the initial number of entries to process without sampling
	Initial int `json:"initial" yaml:"initial"`

	// Thereafter is how often to sample after the initial entries
	Thereafter int `json:"thereafter" yaml:"thereafter"`
}

SamplingConfig defines sampling behavior for high-volume logs.

type SamplingHook

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

SamplingHook implements sampling for high-volume logs.

func NewSamplingHook

func NewSamplingHook(initial, thereafter int) *SamplingHook

NewSamplingHook creates a new sampling hook.

func (*SamplingHook) Fire

func (h *SamplingHook) Fire(entry *Entry) error

Fire executes the hook's logic for a log entry.

func (*SamplingHook) Levels

func (h *SamplingHook) Levels() []Level

Levels returns the levels this hook should be called for.

type TestEntry

type TestEntry struct {
	Level   Level
	Message string
	Fields  []Field
}

TestEntry represents a captured log entry for testing

type TestLogger

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

TestLogger is a Logger implementation for testing that captures logs without producing output and provides methods to verify logging behavior.

func NewTestLogger

func NewTestLogger() *TestLogger

NewTestLogger creates a new TestLogger for use in unit tests

func (*TestLogger) AssertLogged

func (l *TestLogger) AssertLogged(level Level, containsMessage string) bool

AssertLogged returns true if a log entry with the given level and message was captured

func (*TestLogger) AssertLoggedWithField

func (l *TestLogger) AssertLoggedWithField(level Level, containsMessage string, key string, value interface{}) bool

AssertLoggedWithField returns true if a log entry with the given level, message, and field key/value was captured

func (*TestLogger) ClearEntries

func (l *TestLogger) ClearEntries()

ClearEntries clears all captured log entries

func (*TestLogger) Debug

func (l *TestLogger) Debug(msg string, fields ...Field)

Debug logs a debug message

func (*TestLogger) Debugf

func (l *TestLogger) Debugf(format string, args ...interface{})

Debugf logs a formatted debug message

func (*TestLogger) Error

func (l *TestLogger) Error(msg string, fields ...Field)

Error logs an error message

func (*TestLogger) Errorf

func (l *TestLogger) Errorf(format string, args ...interface{})

Errorf logs a formatted error message

func (*TestLogger) Fatal

func (l *TestLogger) Fatal(msg string, fields ...Field)

Fatal logs a fatal message

func (*TestLogger) Fatalf

func (l *TestLogger) Fatalf(format string, args ...interface{})

Fatalf logs a formatted fatal message

func (*TestLogger) GetEntries

func (l *TestLogger) GetEntries() []TestEntry

GetEntries returns all captured log entries

func (*TestLogger) GetLevel

func (l *TestLogger) GetLevel() Level

GetLevel returns the current minimum log level

func (*TestLogger) Info

func (l *TestLogger) Info(msg string, fields ...Field)

Info logs an info message

func (*TestLogger) Infof

func (l *TestLogger) Infof(format string, args ...interface{})

Infof logs a formatted info message

func (*TestLogger) SetLevel

func (l *TestLogger) SetLevel(level Level)

SetLevel sets the minimum log level

func (*TestLogger) Warn

func (l *TestLogger) Warn(msg string, fields ...Field)

Warn logs a warning message

func (*TestLogger) Warnf

func (l *TestLogger) Warnf(format string, args ...interface{})

Warnf logs a formatted warning message

func (*TestLogger) With

func (l *TestLogger) With(fields ...Field) Logger

With returns a new logger with the provided fields added to the context

func (*TestLogger) WithComponent

func (l *TestLogger) WithComponent(component string) Logger

WithComponent returns a new logger with a component field

func (*TestLogger) WithContext

func (l *TestLogger) WithContext(ctx context.Context) Logger

WithContext returns a new logger with context values extracted as fields

func (*TestLogger) WithError

func (l *TestLogger) WithError(err error) Logger

WithError returns a new logger with an error field

func (*TestLogger) WithField

func (l *TestLogger) WithField(key string, value interface{}) Logger

WithField returns a new logger with a field added to the context

func (*TestLogger) WithFields

func (l *TestLogger) WithFields(fields Fields) Logger

WithFields returns a new logger with fields added to the context

type TextFormatter

type TextFormatter struct {
	TimestampFormat  string // Format for timestamps
	EnableCaller     bool   // Enable caller information (default: false)
	DisableColors    bool   // Disable color output
	ShortTimestamp   bool   // Use short timestamp without date (default: false)
	DisableTimestamp bool   // Disable timestamp output
}

TextFormatter formats log entries as human-readable text.

func NewTextFormatter

func NewTextFormatter() *TextFormatter

NewTextFormatter creates a new TextFormatter with sensible defaults.

func (*TextFormatter) Format

func (f *TextFormatter) Format(entry *Entry) ([]byte, error)

Format formats the entry as text.

Jump to

Keyboard shortcuts

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