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:
Type Definition
Constructor Functions
NewTextFormatter
Creates a new TextFormatter with default configuration.EnableColors: trueEnableTimestamp: trueEnableLevel: trueTimestampFormat: “2006/01/02 15:04:05”
- Trace: Cyan
- Debug: HiBlue
- Info: Yellow
- Warn: HiYellow
- Error: Red
- Fatal: HiRed
- Success: Green
NewTextFormatterWithConfig
Creates a new TextFormatter with custom configuration.config- FormatterConfig with custom settings
Methods
Format
Converts a log Entry to formatted text bytes.entry- The log entry to format
[]byte- Formatted text with trailing newlineerror- Always nil for TextFormatter
SetEnableColors
Enables or disables ANSI color codes in output.enabled- true to enable colors, false to disable
SetEnableTimestamp
Enables or disables timestamp output.enabled- true to include timestamps, false to omit
SetEnableLevel
Enables or disables log level output.enabled- true to include level, false to omit
SetTimestampFormat
Sets the timestamp format string.format- Go time format string (e.g., “2006/01/02 15:04:05”)
FormatterConfig
Configuration options for TextFormatter.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
Custom Configuration
Dynamic Configuration
Error Logging
Best Practices
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
Related
- JSONFormatter - Structured JSON formatter
- Logger API - Main logger interface
- Fields - Structured field types