Go Logging
Logging is essential for monitoring your application and debugging errors. Go provides a built-in log package, but many developers use "structured" logging for production.
1. The Standard log Package
This is the simplest way to log. By default, it prints to stderr and includes the date and time.
2. Logging to a File
3. Structured Logging (The Modern Way)
Basic logs are just strings. Structured logs are format-friendly (like JSON), which makes them easy for tools like Datadog or Splunk to search.
While Go's standard library is basic, popular third-party packages include:
- slog (Now part of the standard library in Go 1.21+): Recommended for most apps.
- zap: High performance.
- zerolog: Specialized for high-speed JSON logging.
Example using slog (Standard since 1.21)
Why use a Logger instead of fmt.Println?
- Metadata: Loggers automatically add timestamps and file locations.
- Destinations: Easily switch between terminal output, log files, or network streams.
- Severity Levels: Use levels like
DEBUG,INFO,WARN, andERRORto filter what you see.