Skip to main content

Overview

TextFormatter formats log entries as human-readable text with optional ANSI colors. This is the default formatter for development environments, providing colorful, easy-to-read console output. Output format:
[TIMESTAMP] LEVEL message key=value key2=value2
Example output:
[2026/02/28 17:30:00] INFO connection established host=db.example.com port=5432

Type Definition

type TextFormatter struct {
    config      FormatterConfig
    levelColors map[Level]*color.Color
}

Constructor Functions

NewTextFormatter

Creates a new TextFormatter with default configuration.
func NewTextFormatter() *TextFormatter
Default configuration:
  • EnableColors: true
  • EnableTimestamp: true
  • EnableLevel: true
  • TimestampFormat: “2006/01/02 15:04:05”
Color mapping by level:
  • Trace: Cyan
  • Debug: HiBlue
  • Info: Yellow
  • Warn: HiYellow
  • Error: Red
  • Fatal: HiRed
  • Success: Green
Example:
logger := go_logs.New(
    go_logs.WithFormatter(go_logs.NewTextFormatter()),
)

NewTextFormatterWithConfig

Creates a new TextFormatter with custom configuration.
func NewTextFormatterWithConfig(config FormatterConfig) *TextFormatter
Parameters:
  • config - FormatterConfig with custom settings
Example:
config := go_logs.FormatterConfig{
    EnableColors:    false, // Disable colors for file output
    EnableTimestamp: true,
    EnableLevel:     true,
    TimestampFormat: time.RFC3339,
}
formatter := go_logs.NewTextFormatterWithConfig(config)

Methods

Format

Converts a log Entry to formatted text bytes.
func (f *TextFormatter) Format(entry *Entry) ([]byte, error)
Parameters:
  • entry - The log entry to format
Returns:
  • []byte - Formatted text with trailing newline
  • error - Always nil for TextFormatter
Location: text_formatter.go:82

SetEnableColors

Enables or disables ANSI color codes in output.
func (f *TextFormatter) SetEnableColors(enabled bool)
Parameters:
  • enabled - true to enable colors, false to disable
Use case: Disable colors when writing to files or pipes. Example:
formatter := go_logs.NewTextFormatter()
formatter.SetEnableColors(false) // Plain text output
Location: text_formatter.go:162

SetEnableTimestamp

Enables or disables timestamp output.
func (f *TextFormatter) SetEnableTimestamp(enabled bool)
Parameters:
  • enabled - true to include timestamps, false to omit
Location: text_formatter.go:167

SetEnableLevel

Enables or disables log level output.
func (f *TextFormatter) SetEnableLevel(enabled bool)
Parameters:
  • enabled - true to include level, false to omit
Location: text_formatter.go:172

SetTimestampFormat

Sets the timestamp format string.
func (f *TextFormatter) SetTimestampFormat(format string)
Parameters:
  • format - Go time format string (e.g., “2006/01/02 15:04:05”)
Reference: Go time format constants Example:
formatter.SetTimestampFormat(time.RFC3339)
// Output: 2026-02-28T17:30:00Z
Location: text_formatter.go:178

FormatterConfig

Configuration options for TextFormatter.
type FormatterConfig struct {
    EnableColors    bool   // Enable ANSI color codes (TextFormatter only)
    EnableTimestamp bool   // Include timestamp in output
    EnableLevel     bool   // Include log level in output
    TimestampFormat string // Format string for timestamps
}

Field Formatting

TextFormatter formats structured fields as key=value pairs with special handling:
  • Strings with spaces: Quoted as key="value with spaces"
  • Strings without spaces: Unquoted as key=value
  • Errors: Formatted as error=error_message
  • Other types: Formatted using fmt.Sprintf("%v")

Usage Examples

Basic Usage

import "github.com/drossan/go_logs"

logger := go_logs.New(
    go_logs.WithFormatter(go_logs.NewTextFormatter()),
)

logger.Info("Server started",
    go_logs.Int("port", 8080),
    go_logs.String("env", "production"),
)
// Output: [2026/02/28 17:30:00] INFO Server started port=8080 env=production

Custom Configuration

// Disable colors for file output
config := go_logs.FormatterConfig{
    EnableColors:    false,
    EnableTimestamp: true,
    EnableLevel:     true,
    TimestampFormat: time.RFC3339,
}

formatter := go_logs.NewTextFormatterWithConfig(config)
logger := go_logs.New(go_logs.WithFormatter(formatter))

Dynamic Configuration

formatter := go_logs.NewTextFormatter()

// Disable colors when redirecting to file
if isOutputFile {
    formatter.SetEnableColors(false)
}

// Use ISO 8601 timestamps
formatter.SetTimestampFormat(time.RFC3339)

logger := go_logs.New(go_logs.WithFormatter(formatter))

Error Logging

err := someOperation()
if err != nil {
    logger.Error("Operation failed",
        go_logs.Err(err),
        go_logs.String("operation", "database query"),
    )
    // Output: [2026/02/28 17:30:00] ERROR Operation failed error=connection timeout operation="database query"
}

Best Practices

Development vs ProductionUse TextFormatter for development and JSONFormatter for production:
var formatter go_logs.Formatter
if os.Getenv("ENV") == "production" {
    formatter = go_logs.NewJSONFormatter()
} else {
    formatter = go_logs.NewTextFormatter()
}
Color SupportANSI colors may not work correctly in all environments. Disable colors when:
  • Writing to files
  • Using pipes
  • Running in CI/CD environments
  • Windows terminals without ANSI support

Performance

TextFormatter is optimized for development use:
  • Fast formatting: ~220.6 ns/op
  • Minimal allocations: Only allocates for final buffer
  • Buffered writes: Uses bytes.Buffer for efficiency

Build docs developers (and LLMs) love