Error Handling
Handle startup errors, runtime failures, and panic logging using structured slog-compatible logging with automatic JSON file output.
The router package integrates directly with Go’s standard log/slog ecosystem.
Application errors, startup failures, and recovered panics can be logged using structured logging handlers such as:
github.com/netlifeguru/logger- custom
slog.Handler - JSON loggers
- external observability systems
This allows production applications to store structured error logs in machine-readable formats for monitoring and debugging.
Startup Errors
Server startup failures should always be checked.
Example:
if err := r.ListenAndServe(":8000"); err != nil {
slog.Error("failed to start server", "error", err)
os.Exit(1)
}This logs startup errors such as:
- port conflicts
- permission issues
- invalid listener configuration
- TLS failures
Structured JSON Logging
When used together with github.com/netlifeguru/logger, errors are automatically written into rotating JSON log files.
Example logger setup:
closer, err := logger.Init(logger.Config{
Dir: "./logs",
TerminalOutput: true,
})Example log file:
./logs/2026-05-12-0001.logExample structured error log:
{
"time": "2026-05-12T21:43:02+02:00",
"level": "ERROR",
"msg": "failed to start server",
"error": "listen tcp :8000: bind: address already in use"
}Structured logs make it easier to integrate with:
- Elasticsearch
- Loki
- Datadog
- Grafana
- Splunk
- cloud logging systems
Panic Recovery Logging
Recovered panics are also logged automatically through slog.
Example panic:
panic("database connection lost")Example log output:
{
"time": "2026-05-12T21:50:11+02:00",
"level": "ERROR",
"msg": "panic recovered",
"panic": "database connection lost"
}This allows applications to capture unexpected runtime failures without crashing the server process.
Terminal vs File Logging
When terminal output is enabled:
TerminalOutput: trueerrors are shown in the console with colorized formatting.
Example:
2026-05-12 21:43:02 [ERROR] failed to start server error="bind: address already in use"At the same time, the same event is safely written into structured JSON log files.
Recommended Production Setup
Recommended production configuration:
logger.Init(logger.Config{
Dir: "./logs",
TerminalOutput: false,
MinLevel: slog.LevelInfo,
ConsoleMinLevel: slog.LevelError,
})This configuration:
- stores structured logs in files
- reduces terminal noise
- keeps error logs centralized
- enables long-term log retention
Notes
The router itself does not force a logging implementation.
All logging flows through Go’s standard log/slog package, allowing applications to fully control:
- formatting
- storage
- rotation
- transports
- observability integrations
- structured metadata