Documentation
¶
Overview ¶
Package zlog provides a minimal, production-ready logging facade over Uber's zap. It exposes a small interface (ZLogger) that works with a zap-backed implementation in production and a safe stdlib fallback when zap cannot be initialized.
Key features:
- Simple interface: Info, Warn, Error, Debug, With, Sync
- Dev/Prod presets via env: APP_DEBUG, LOG_FORMAT
- JSON or console encoders
- Context helpers: Attach, FromContext, FromContextDiscard
- Stdlib integration: redirect the global log package to zlog
- No-op logger: Discard
Environment variables:
APP_DEBUG = "true" | "1" (enables development mode) LOG_FORMAT = "json" | "console"
Quick start:
lg := zlog.NewDefault("my-service")
defer lg.Sync()
lg.Info("started", zlog.String("port", "8080"))
Redirect the global log package at a specific level:
restore := lg.RedirectStdLog(zapcore.WarnLevel)
defer restore()
log.Println("this becomes WARN in zlog")
Context usage:
ctx := zlog.Attach(context.Background(), lg)
zlog.FromContext(ctx).Info("request", zlog.String("path", "/health"))
Index ¶
- Constants
- func Attach(ctx context.Context, lg ZLogger) context.Context
- func DebugFromEnv() bool
- func FormatFromEnv(defaultFormat string) string
- func RedirectStdLogOutput(w io.Writer) (restore func())
- func RedirectStdLogger(lg ZLogger, lvl zapcore.Level) (restore func())
- func StdLoggerAt(lg ZLogger, lvl zapcore.Level) *log.Logger
- type Config
- type Field
- func Any(key string, value any) Field
- func Bool(key string, value bool) Field
- func Error(key string, value error) Field
- func Float64(key string, value float64) Field
- func Int(key string, value int) Field
- func Int32(key string, value int32) Field
- func String(key, value string) Field
- func Time(key string, value time.Time) Field
- type ZLogger
Examples ¶
Constants ¶
const ( // ZLoggerJsonFormat selects JSON encoding for logs. ZLoggerJsonFormat = "json" // ZLoggerConsoleFormat selects console (human-friendly) encoding for logs. ZLoggerConsoleFormat = "console" )
Variables ¶
This section is empty.
Functions ¶
func Attach ¶
Attach returns a new context with the provided ZLogger stored inside.
Example ¶
package main
import (
"context"
"github.com/azargarov/go-utils/zlog"
)
func main() {
lg := zlog.NewDefault("svc")
defer lg.Sync()
ctx := zlog.Attach(context.Background(), lg)
zlog.FromContext(ctx).Info("request", zlog.String("path", "/health"))
// Logs are not written to stdout; nothing should be captured here.
Output:
func DebugFromEnv ¶
func DebugFromEnv() bool
DebugFromEnv returns true if APP_DEBUG is "true" (case-insensitive) or "1".
func FormatFromEnv ¶
FormatFromEnv returns LOG_FORMAT if set; otherwise defaultFormat or "json".
func RedirectStdLogOutput ¶
RedirectStdLogOutput redirects the global log package to the provided writer. It returns a restore function that reverts log's output, flags, and prefix.
func RedirectStdLogger ¶
RedirectStdLogger redirects the global log package to lg at the given level. It returns a restore function that reverts log's output, flags, and prefix.
Types ¶
type Config ¶
type Config struct {
// ServiceName is injected as initial structured field "service".
ServiceName string
// Debug enables development mode (colorized console, debug level).
Debug bool
// Format selects encoder: "json" or "console".
Format string // "json" or "console"
// ForceStderr routes all output to stderr when true.
ForceStderr bool // route all logs to stderr
}
Config holds logging configuration options for New.
type Field ¶
Field is a structured log field, aliasing zapcore.Field. Use helper constructors like String, Int, Bool, etc. to create fields.
type ZLogger ¶
type ZLogger interface {
Info(msg string, fields ...Field)
Error(msg string, fields ...Field)
With(fields ...Field) ZLogger
Sync() error
Debug(msg string, fields ...Field)
Warn(msg string, fields ...Field)
RedirectStdLog(level zapcore.Level) (restore func())
RedirectOutput(w io.Writer, level zapcore.Level) (restore func())
}
ZLogger is the minimal interface implemented by zlog's backends. It supports structured fields, contextual enrichment via With, and Sync.
var Discard ZLogger = noopLogger{}
Discard is a ZLogger that drops all logs. It can be used globally.
func FromContext ¶
FromContext retrieves a ZLogger from ctx or returns a stdlib fallback logger if none is present. The fallback never panics and prints key=value fields.
func FromContextDiscard ¶
FromContextDiscard retrieves a ZLogger from ctx or returns a no-op logger (Discard) that drops all output. Useful in tests and benchmarks.
func New ¶
New builds a zap-backed ZLogger using cfg. If zap initialization fails, New returns a stdlib-backed fallback logger that never panics.
func NewDefault ¶
NewDefault creates a logger with defaults derived from environment variables. It sets the "service" field to serviceName.
Example ¶
package main
import (
"github.com/azargarov/go-utils/zlog"
)
func main() {
lg := zlog.NewDefault("my-service")
defer lg.Sync()
lg.Info("started",
zlog.String("env", "dev"),
zlog.Int("port", 8080),
)
// Logs are not written to stdout; nothing should be captured here.
Output:
func NewDiscard ¶
func NewDiscard() ZLogger
NewDiscard returns a new no-op ZLogger that drops all logs.