zerowrap
A reusable Go package that wraps zerolog with context-based logger access and maximum abstraction.
Installation
go get bnema.dev/zerowrap
For OpenTelemetry integration (optional):
go get bnema.dev/zerowrap/otel
Quick Start
package main
import (
"context"
"bnema.dev/zerowrap"
)
func main() {
// Create a logger and attach to context
logger := zerowrap.New(zerowrap.Config{
Level: "debug",
Format: "console",
})
ctx := zerowrap.WithCtx(context.Background(), logger)
// Use throughout your application
log := zerowrap.FromCtx(ctx)
log.Info().Msg("hello world")
// Pass context to other functions
doSomething(ctx)
}
func doSomething(ctx context.Context) {
log := zerowrap.FromCtx(ctx)
log.Debug().Msg("doing something")
}
Features
- Context-based logger storage and retrieval
- Add fields to loggers (single, multiple, or from structs)
- Configurable logger creation with sensible defaults
- File-based logging with rotation support and app-managed log paths
- OpenTelemetry log bridging (optional sub-package)
- Common field name constants for consistency
- Error helpers for logging and returning errors in one line
API Reference
Context Functions
| Function | Description |
|---|---|
FromCtx(ctx) |
Extract logger from context (returns no-op if none) |
Ctx(ctx) |
Get pointer to logger in context |
WithCtx(ctx, log) |
Attach logger to context |
Field Helpers
| Function | Description |
|---|---|
FromCtxWithField(ctx, key, value) |
Get logger with one additional field |
FromCtxWithFields(ctx, fields) |
Get logger with multiple fields |
FromCtxWithStruct(ctx, struct) |
Get logger with fields from struct tags |
CtxWithField(ctx, key, value) |
Get new context with enriched logger |
CtxWithFields(ctx, fields) |
Get new context with enriched logger |
CtxWithStruct(ctx, struct) |
Get new context with enriched logger |
Logger Creation
| Function | Description |
|---|---|
New(cfg) |
Create logger with configuration |
NewFromEnv(prefix) |
Create logger from environment variables |
NewWithFile(cfg, fileCfg) |
Create logger with file output |
Default() |
Create default logger (info level, console format) |
WithHook(log, hook) |
Add hook to logger |
Error Helpers (Logger methods)
| Method | Description |
|---|---|
log.WrapErr(err, msg) |
Log and wrap error with message |
log.WrapErrWithFields(err, msg, fields) |
Log and wrap error with fields |
log.WrapErrf(err, format, args...) |
Log and wrap error with formatted message |
Usage Examples
Basic Logging with Context
logger := zerowrap.Default()
ctx := zerowrap.WithCtx(context.Background(), logger)
log := zerowrap.FromCtx(ctx)
log.Info().Str("action", "start").Msg("application started")
Adding Fields
// Single field
log := zerowrap.FromCtxWithField(ctx, "user_id", 123)
log.Info().Msg("user action")
// Multiple fields
log := zerowrap.FromCtxWithFields(ctx, map[string]any{
"user_id": 123,
"request_id": "abc-123",
"ip": "192.168.1.1",
})
log.Info().Msg("request received")
// Enrich context for downstream use
ctx = zerowrap.CtxWithField(ctx, zerowrap.FieldComponent, "auth")
zerowrap.FromCtx(ctx).Info().Msg("authenticating") // includes component=auth
Struct Tags
Extract fields from structs using the log tag (falls back to json tag, then field name):
type RequestInfo struct {
UserID int `log:"user_id"`
RequestID string `log:"request_id"`
IP string `json:"ip_address"`
Internal string `log:"-"` // skipped
}
info := RequestInfo{
UserID: 123,
RequestID: "abc-123",
IP: "192.168.1.1",
Internal: "secret",
}
log := zerowrap.FromCtxWithStruct(ctx, info)
log.Info().Msg("request info")
// Output includes: user_id=123 request_id=abc-123 ip_address=192.168.1.1
Logger Configuration
log := zerowrap.New(zerowrap.Config{
Level: "debug", // trace, debug, info, warn, error, fatal, panic
Format: "console", // console or json
TimeFormat: time.RFC3339, // custom time format
Output: os.Stdout, // custom output writer
Caller: true, // include caller info (file:line)
})
Environment Variables
// Reads MYAPP_LOG_LEVEL and MYAPP_LOG_FORMAT
log := zerowrap.NewFromEnv("MYAPP")
File Logging
log, cleanup, err := zerowrap.NewWithFile(
zerowrap.Config{
Level: "info",
Format: "console",
},
zerowrap.FileConfig{
Enabled: true,
Path: "/var/log/myapp/app.log",
MaxSize: 100, // MB
MaxBackups: 3,
MaxAge: 28, // days
Compress: true,
},
)
if err != nil {
panic(err)
}
defer cleanup()
ctx := zerowrap.WithCtx(context.Background(), log)
// Logs go to both console (formatted) and file (JSON)
Error Handling
Log and return errors in one line using Logger methods:
func connectDB(ctx context.Context) error {
log := zerowrap.FromCtx(ctx)
db, err := sql.Open("postgres", connStr)
if err != nil {
return log.WrapErr(err, "failed to open database")
}
if err := db.Ping(); err != nil {
return log.WrapErr(err, "database ping failed")
}
return nil
}
// With fields
func queryUser(ctx context.Context, userID int) (*User, error) {
log := zerowrap.FromCtx(ctx)
user, err := db.GetUser(userID)
if err != nil {
return nil, log.WrapErrWithFields(err, "user query failed", map[string]any{
"user_id": userID,
})
}
return user, nil
}
// With formatted message
func connectToHost(ctx context.Context, host string) error {
log := zerowrap.FromCtx(ctx)
conn, err := net.Dial("tcp", host)
if err != nil {
return log.WrapErrf(err, "failed to connect to %s", host)
}
defer conn.Close()
return nil
}
App-Managed File Logging
When you don't want to hard-code a full file path, set AppName and let zerowrap
choose the standard OS-specific log directory:
fileCfg := zerowrap.FileConfig{
Enabled: true,
AppName: "MyApp",
Mode: zerowrap.FileModeSession,
FileFormat: zerowrap.FileFormatConsole,
}
// Inspect the resolved path without creating a logger
path, err := zerowrap.ResolveLogPath(fileCfg)
if err != nil {
panic(err)
}
fmt.Println("Log file:", path)
log, cleanup, err := zerowrap.NewWithFile(
zerowrap.Config{Level: "debug", Format: "console"},
fileCfg,
)
if err != nil {
panic(err)
}
defer cleanup()
Default OS locations (when no BaseDir override is supplied):
| OS | Log root |
|---|---|
| macOS | ~/Library/Logs/<AppName>/ |
| Linux | $XDG_STATE_HOME/<AppName>/logs/ or ~/.local/state/<AppName>/logs/ |
| Windows | %LOCALAPPDATA%\<AppName>\Logs\ |
Modes
| Constant | Behavior |
|---|---|
FileModeSingle |
Writes to <root>/app.log (or <root>/<Name>.log). All runs share the same file. |
FileModeSession |
Writes to <root>/sessions/<session-id>/<Name>.log (default app.log). Each process generates a unique session directory that is shared across all loggers in that process. |
File formats
| Constant | Description |
|---|---|
FileFormatJSON |
JSON lines (default). Best for ingestion and log aggregation. |
FileFormatConsole |
Human-readable text without ANSI colors. Useful for local apps, CLI tools, and support logs. |
When both Path and AppName are set, Path takes priority. Set BaseDir to
relocate the app root while keeping the standard layout. For example,
BaseDir: "/tmp" with AppName: "MyApp" resolves under /tmp/MyApp/logs/.
Compatibility note: FileConfig is intended to be used with keyed fields. This
release adds fields to FileConfig, so callers using unkeyed composite literals
should switch to keyed literals.
OpenTelemetry Integration
import (
"bnema.dev/zerowrap"
"bnema.dev/zerowrap/otel"
)
// Using global provider
log := zerowrap.New(cfg).Hook(otel.NewHook("my-service"))
// Using custom provider
provider := // your OTel logger provider
log := zerowrap.New(cfg).Hook(otel.NewHookWithProvider(provider, "my-service"))
ctx := zerowrap.WithCtx(context.Background(), log)
// Logs now flow to both zerolog output AND OpenTelemetry
Field Constants
Common field names for consistency across your application:
// Identity & Tracing
zerowrap.FieldComponent // "component"
zerowrap.FieldRequestID // "request_id"
zerowrap.FieldTraceID // "trace_id"
zerowrap.FieldSpanID // "span_id"
zerowrap.FieldCorrelationID // "correlation_id"
zerowrap.FieldSessionID // "session_id"
zerowrap.FieldUserID // "user_id"
// HTTP/API
zerowrap.FieldMethod // "method"
zerowrap.FieldPath // "path"
zerowrap.FieldStatus // "status"
zerowrap.FieldClientIP // "client_ip"
// Service/Infra
zerowrap.FieldService // "service"
zerowrap.FieldVersion // "version"
zerowrap.FieldHost // "host"
zerowrap.FieldEnv // "env"
// Operations
zerowrap.FieldAction // "action"
zerowrap.FieldOperation // "operation"
zerowrap.FieldError // "error"
zerowrap.FieldDuration // "duration_ms"
// Data
zerowrap.FieldCount // "count"
zerowrap.FieldSize // "size_bytes"
// Clean Architecture - Layers
zerowrap.FieldLayer // "layer" (domain, usecase, adapter)
zerowrap.FieldUseCase // "usecase" (e.g., "CreateUser")
// Clean Architecture - Adapters
zerowrap.FieldAdapter // "adapter" (http, grpc, postgres)
zerowrap.FieldAdapterType // "adapter_type" (in/out)
zerowrap.FieldHandler // "handler"
zerowrap.FieldRepository // "repository"
zerowrap.FieldGateway // "gateway"
// Database/Storage
zerowrap.FieldTable // "table"
zerowrap.FieldQuery // "query"
zerowrap.FieldDatabase // "database"
// Messaging/Events
zerowrap.FieldEvent // "event"
zerowrap.FieldTopic // "topic"
zerowrap.FieldQueue // "queue"
zerowrap.FieldPayload // "payload"
// Entity/Resource
zerowrap.FieldEntity // "entity"
zerowrap.FieldEntityID // "entity_id"
zerowrap.FieldEntityType // "entity_type"
Usage:
ctx = zerowrap.CtxWithField(ctx, zerowrap.FieldComponent, "database")
ctx = zerowrap.CtxWithField(ctx, zerowrap.FieldRequestID, requestID)
License
MIT License - see LICENSE file.