Overview
JSONFormatter formats log entries as JSON for log aggregators and production environments. Ideal for use with ELK Stack, Loki, Datadog, and other log analysis systems.
Output format (single line):
Type Definition
Constructor Functions
NewJSONFormatter
Creates a new JSONFormatter with default configuration.EnableTimestamp: trueEnableLevel: trueTimestampFormat: RFC3339 (ISO 8601)
NewJSONFormatterWithConfig
Creates a new JSONFormatter with custom configuration.config- FormatterConfig with custom settings
Methods
Format
Converts a log Entry to JSON bytes.entry- The log entry to format
[]byte- JSON bytes with trailing newlineerror- Error if JSON marshaling fails
SetEnableTimestamp
Enables or disables timestamp output.enabled- true to include timestamps, false to omit
SetEnableLevel
Enables or disables level output.enabled- true to include level, false to omit
SetTimestampFormat
Sets the timestamp format string.format- Go time format string (default: RFC3339)
JSONLogEntry Structure
Internal JSON structure used for marshaling.Timestamp- ISO 8601 timestamp (omitted if disabled)Level- Log level as uppercase string (e.g., “INFO”, “ERROR”)Message- The log messageFields- Nested object with structured fields (omitted if empty)Caller- Source file and line (e.g., “main.go:42”)CallerFunc- Function name (e.g., “main.processRequest”)StackTrace- Stack trace for errors (omitted if empty)
Field Type Handling
JSONFormatter handles different field types appropriately:- Strings: Properly escaped JSON strings
- Numbers: Native JSON numbers (int, float64)
- Booleans: JSON booleans (true/false)
- Errors: Converted to error message string using
.Error() - Nil errors: Represented as JSON null
- Other types: Marshaled according to encoding/json rules
Usage Examples
Basic Production Setup
Error Logging with Stack Traces
Custom Timestamp Format
Minimal JSON (No Timestamp/Level)
With Caller Information
Integration Examples
ELK Stack (Elasticsearch + Logstash + Kibana)
Datadog
Grafana Loki
Best Practices
Performance
JSONFormatter is optimized for production use:- Fast marshaling: ~249.3 ns/op
- Standard library: Uses encoding/json (no dependencies)
- Single allocation: Creates one map for fields
- Proper escaping: Handles special characters correctly
Output Format Details
With All Fields
Minimal Format
Related
- TextFormatter - Human-readable text formatter
- Logger API - Main logger interface
- Fields - Structured field types