Overview
Structured logging allows you to attach typed key-value pairs (fields) to log messages instead of concatenating strings. This makes logs:- Searchable: Query by specific fields in log aggregators (ELK, Loki, Datadog)
- Machine-readable: Parse and analyze logs programmatically
- Type-safe: Typed helpers prevent common formatting errors
- Zero-allocation: Fields are simple structs with no heap allocations
Field Types
go_logs provides typed field constructors for common data types:Field Type Definitions
Each field is a simple struct with zero allocations:field.go
Basic Usage
Simple Fields
- Text Output
- JSON Output
Error Fields
TheErr() helper automatically sets the key to "error":
Multiple Fields
Field Methods
Fields expose accessor methods for formatters and hooks:Real-World Examples
HTTP Request Logging
Database Operation Logging
System Metrics Logging
Field Formatting
Text Formatter
The TextFormatter formats fields askey=value pairs:
- Strings with spaces are quoted:
message="hello world" - Strings without spaces are unquoted:
status=success - Errors use
.Error()method:error=connection refused - Other types use
fmt.Sprintf("%v"):count=42 rate=3.14
text_formatter.go
JSON Formatter
The JSONFormatter includes fields as a nested object:json_formatter.go
Performance
Fields are designed for zero-allocation creation:- Field creation: 0.34 ns/op, 0 allocs/op
- Simple struct construction with no heap allocations
- Type information stored in enum for fast switches
Best Practices
Use consistent field names
Use consistent field names
Standardize field names across your application for easier searching:
Use typed helpers instead of Any()
Use typed helpers instead of Any()
Prefer typed helpers for better performance and type safety:
Don't log sensitive data
Don't log sensitive data
Avoid logging passwords, tokens, credit cards, etc.:
Keep messages human-readable
Keep messages human-readable
The message should be readable without fields:
Next Steps
Child Loggers
Learn how to create child loggers with inherited fields
Context Propagation
Automatically include trace_id and span_id from context