Overview
The hook system provides extensibility points for processing log entries. Hooks are called after an entry is created but before it’s written, allowing you to:- Send notifications (Slack, email, PagerDuty)
- Collect metrics and statistics
- Filter or transform log data
- Implement custom storage backends
- Trigger alerts on specific conditions
Hook Interface
All hooks must implement theHook interface from ~/workspace/source/hook.go:75-79:
Run method is called for every log entry that passes level filtering. If a hook returns an error, it’s logged to stderr but doesn’t fail the log entry.
Creating Simple Hooks
Using HookFunc
For simple hooks that don’t need state, useHookFunc from ~/workspace/source/hook.go:14:
Using NewFuncHook
Alternatively, useNewFuncHook from ~/workspace/source/hook.go:45:
Implementing Complex Hooks
For hooks that need state or configuration, implement theHook interface:
Multiple Hooks
Register multiple hooks to run in sequence from~/workspace/source/options.go:49:
Accessing Entry Data
Hooks receive a completeEntry object from ~/workspace/source/entry.go:11-31:
Reading Fields
Hook Execution Flow
From~/workspace/source/logger_impl.go:192-197:
- Entry is created with timestamp and fields
- Caller info captured (if enabled)
- Stack trace captured (if enabled)
- Redactor applied (if configured)
- Hooks execute (in registration order)
- Entry formatted and written
Best Practices
Performance
- Keep hooks fast: Hooks run synchronously in the logging path
- Use goroutines for slow operations:
Error Handling
- Always return errors for debugging
- Don’t panic in hooks
- Log hook failures to a separate channel:
Level Filtering
- Filter early to avoid unnecessary work:
Thread Safety
Hooks may be called concurrently from multiple goroutines. Ensure your hook is thread-safe:Common Use Cases
Metrics Collection
Error Notifications
Audit Logging
Testing Hooks
See Also
- Metrics - Built-in metrics collection
- Redaction - Sensitive data masking
- Caller Info - Capture calling function details