zlog

package module
v0.2.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 25, 2025 License: MIT Imports: 13 Imported by: 1

README

zlog

Lightweight, production-ready logging library built on top of Uber’s zap.

Provides:

  • Unified interface ZLogger for structured logs
  • Dev / Prod presets (APP_DEBUG, LOG_FORMAT)
  • JSON or console output
  • Context helpers (Attach, FromContext)
  • Safe stdlib fallback (defaultLogger)
  • No-op logger (Discard)
  • Stdlog redirection (RedirectStdLog, RedirectOutput)

Install

go get github.com/azargarov/go-utils/zlog
import "github.com/azargarov/go-utils/zlog"

Quick start

lg := zlog.NewDefault("my-service")
defer lg.Sync()

lg.Info("started",
    zlog.String("env", "dev"),
    zlog.Int("port", 8080),
)

Config

cfg := &zlog.Config{
    ServiceName: "my-service",
    Debug:       false,
    Format:      zlog.ZLoggerJsonFormat,
    ForceStderr: false,
}
lg := zlog.New(cfg)

Environment variables:

Variable Values Description
APP_DEBUG true / 1 Enables dev mode
LOG_FORMAT json / console Output format

Context helpers

ctx := zlog.Attach(context.Background(), lg)
zlog.FromContext(ctx).Info("req", zlog.String("path", "/health"))

FromContextDiscard() returns a silent no-op logger.


Fields

zlog.String("user", "alice")
zlog.Int("age", 30)
zlog.Bool("ok", true)
zlog.Float64("score", 0.97)
zlog.Error("err", err)
zlog.Time("at", time.Now())

Stdlog redirection

Redirect global log output:

restore := lg.RedirectStdLog(zapcore.WarnLevel)
defer restore()
log.Println("stdlib message") // -> WARN in zlog

Redirect output to a custom writer:

f, _ := os.Create("/tmp/app.log")
restore := lg.RedirectOutput(f, zapcore.InfoLevel)
defer restore()
lg.Info("written to /tmp/app.log")

Interface

type ZLogger interface {
    Info(msg string, fields ...Field)
    Error(msg string, fields ...Field)
    Debug(msg string, fields ...Field)
    Warn(msg string, fields ...Field)
    With(fields ...Field) ZLogger
    Sync() error
    RedirectStdLog(level zapcore.Level) (restore func())
    RedirectOutput(w io.Writer, level zapcore.Level) (restore func())
}

Fallback safety

If zap initialization fails, zlog falls back to a stdlib logger that prints flat key=value pairs and never panics.


Example output

JSON

{"level":"info","timestamp":"2025-10-25T12:34:56Z","msg":"started","service":"my-service","port":8080}

Console

2025-10-25T12:34:56Z INFO started service=my-service port=8080

License

MIT © Andrey Zargarov

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

Examples

Constants

View Source
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

func Attach(ctx context.Context, lg ZLogger) context.Context

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.
	

func DebugFromEnv

func DebugFromEnv() bool

DebugFromEnv returns true if APP_DEBUG is "true" (case-insensitive) or "1".

func FormatFromEnv

func FormatFromEnv(defaultFormat string) string

FormatFromEnv returns LOG_FORMAT if set; otherwise defaultFormat or "json".

func RedirectStdLogOutput

func RedirectStdLogOutput(w io.Writer) (restore func())

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

func RedirectStdLogger(lg ZLogger, lvl zapcore.Level) (restore func())

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.

func StdLoggerAt

func StdLoggerAt(lg ZLogger, lvl zapcore.Level) *log.Logger

StdLoggerAt returns a *log.Logger that writes to lg at the provided zapcore level. If lg is zap-backed, it uses zap.NewStdLogAt; otherwise it adapts via io.Writer.

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

type Field = zapcore.Field

Field is a structured log field, aliasing zapcore.Field. Use helper constructors like String, Int, Bool, etc. to create fields.

func Any

func Any(key string, value any) Field

String constructs a string field

func Bool

func Bool(key string, value bool) Field

Bool constructs a bool field.

func Error

func Error(key string, value error) Field

Error constructs a named error field.

func Float64

func Float64(key string, value float64) Field

Float64 constructs a float64 field.

func Int

func Int(key string, value int) Field

Int constructs an int field.

func Int32

func Int32(key string, value int32) Field

Int32 constructs an int32 field.

func String

func String(key, value string) Field

String constructs a string field.

func Time

func Time(key string, value time.Time) Field

Time constructs a time.Time field.

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

func FromContext(ctx context.Context) ZLogger

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

func FromContextDiscard(ctx context.Context) ZLogger

FromContextDiscard retrieves a ZLogger from ctx or returns a no-op logger (Discard) that drops all output. Useful in tests and benchmarks.

func New

func New(cfg *Config) ZLogger

New builds a zap-backed ZLogger using cfg. If zap initialization fails, New returns a stdlib-backed fallback logger that never panics.

func NewDefault

func NewDefault(serviceName string) ZLogger

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.
	

func NewDiscard

func NewDiscard() ZLogger

NewDiscard returns a new no-op ZLogger that drops all logs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL