zaplog

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 15 Imported by: 2

README

zaplog

Simple packaging for zap with OpenTelemetry hooks.

Install

go get github.com/vearne/zaplog

Init

// defaults: level=info, output=stdout
zlog.InitLogger()

// file only
zlog.InitLogger(zlog.WithFile("/var/log/app.log"), zlog.WithLevel("debug"))

// file + stdout, JSON (typical container setup)
zlog.InitLogger(
    zlog.WithFile("/var/log/app.log"),
    zlog.WithStdout(),
    zlog.WithJSON(),
    zlog.WithLevel("info"),
)

defer zlog.Sync()
Options
Option Meaning
WithLevel(string) debug / info / warn / error (default info)
WithFile(path) lumberjack file output
WithStdout() / WithStderr() std sinks
WithJSON() JSON encoder instead of console
WithCallerSkip(n) extra caller frames to skip (default 1)
WithTraceID / WithAutoEvents OTEL helpers
WithMaxSize / WithMaxAge / WithMaxBackups / WithCompress rotation

Output rule: if no output option is set, stdout is used. Once any of WithFile / WithStdout / WithStderr is set, only those sinks are enabled.

Runtime
zlog.SetLevel("debug")
_ = zlog.Sync() // flush before exit
Named

Named() returns *otelzap.Logger and bypasses package helpers (statistics / trace_id / auto span events). Use package-level Info / InfoContext when you need those.

Examples

Runnable demos live under example/. See example/README.md.

go run ./example/basic
go run ./example/file
go run ./example/teeJSON
go run ./example/noContext      # + Prometheus on :9090
go run ./example/withContext   # + trace_id / span events

Minimal snippet

package main

import (
	zlog "github.com/vearne/zaplog"
	"go.uber.org/zap"
)

func main() {
	if err := zlog.InitLogger(); err != nil {
		panic(err)
	}
	defer zlog.Sync()

	zlog.Info("hello", zap.String("from", "zaplog"))
}

Documentation

Index

Constants

View Source
const LabelLevel = "level"

Variables

View Source
var (
	// DefaultLogger is never nil: before InitLogger it discards all logs (zap.NewNop).
	DefaultLogger = otelzap.New(zap.NewNop())
)

Functions

func AtomicLevel added in v0.2.0

func AtomicLevel() zap.AtomicLevel

AtomicLevel returns the underlying zap.AtomicLevel for advanced use.

func Debug

func Debug(msg string, fields ...zapcore.Field)

func DebugContext added in v0.0.2

func DebugContext(ctx context.Context, msg string, fields ...zapcore.Field)

func Error

func Error(msg string, fields ...zapcore.Field)

func ErrorContext added in v0.0.2

func ErrorContext(ctx context.Context, msg string, fields ...zapcore.Field)

func Fatal

func Fatal(msg string, fields ...zapcore.Field)

func FatalContext added in v0.0.2

func FatalContext(ctx context.Context, msg string, fields ...zapcore.Field)

func GetDefaultLogger

func GetDefaultLogger() *otelzap.Logger

func GetTraceID added in v0.1.0

func GetTraceID(ctx context.Context) string

GetTraceID returns the 32-character lowercase hexadecimal string of the TraceID from the current context. Returns an empty string if there is no Span in the ctx.

func Info

func Info(msg string, fields ...zapcore.Field)

func InfoContext added in v0.0.2

func InfoContext(ctx context.Context, msg string, fields ...zapcore.Field)

func InitLogger

func InitLogger(opts ...Option) error

InitLogger initializes the default logger.

Defaults when called with no options:

  • level: info
  • output: stdout

Examples:

InitLogger()
InitLogger(WithFile("/var/log/app.log"))
InitLogger(WithFile(path), WithStdout(), WithLevel("debug"), WithJSON())

func Level added in v0.2.0

func Level() zapcore.Level

Level returns the current minimum log level.

func Named added in v0.0.5

func Named(s string) *otelzap.Logger

Named returns a child logger with the given name.

Logs written through the returned *otelzap.Logger bypass zaplog package helpers: they do NOT go through statistics / trace_id injection / auto span events. Use package-level Info/InfoContext/... when you need those features.

func SetLevel added in v0.2.0

func SetLevel(level string) error

SetLevel changes the minimum log level at runtime. Supported: debug, info, warn, error. Must be called after InitLogger.

func Sync added in v0.2.0

func Sync() error

Sync flushes any buffered log entries. Call before process exit.

func Warn

func Warn(msg string, fields ...zapcore.Field)

func WarnContext added in v0.0.2

func WarnContext(ctx context.Context, msg string, fields ...zapcore.Field)

Types

type Config added in v0.1.0

type Config struct {
	lumberjack.Logger
	WithTraceID    bool
	WithAutoEvents bool
	// CallerSkip is the number of additional stack frames to skip when
	// reporting the caller. Default is 1 (skip zaplog's own Info/Debug/... wrappers).
	// Increase by 1 for each extra wrapper layer around zaplog.
	CallerSkip int

	Level string

	// Output sinks. If none are set, InitLogger defaults to stdout.
	FilePath   string
	AlsoStdout bool
	AlsoStderr bool

	JSON bool
	// contains filtered or unexported fields
}

type Option added in v0.0.7

type Option func(c *Config)

func WithAutoEvents added in v0.1.1

func WithAutoEvents(enable bool) Option

WithAutoEvents configures the logger to automatically add log messages as events to active spans. When enabled, each log call will add an event to the current span with the log level and message.

func WithCallerSkip added in v0.2.0

func WithCallerSkip(skip int) Option

WithCallerSkip sets how many extra stack frames to skip when annotating logs with caller file:line. The default is 1 so direct zaplog.Info/Debug/... calls report the application call site. Pass 2 if you wrap zaplog in another package (e.g. applog.Info -> zaplog.Info).

func WithCompress added in v0.0.7

func WithCompress(compress bool) Option

func WithFile added in v0.2.0

func WithFile(path string) Option

WithFile enables file output at path (lumberjack rotation).

func WithJSON added in v0.2.0

func WithJSON() Option

WithJSON switches the encoder from console to JSON.

func WithLevel added in v0.2.0

func WithLevel(level string) Option

WithLevel sets the minimum log level. Supported: debug, info, warn, error. Default is "info".

func WithMaxAge added in v0.0.7

func WithMaxAge(days int) Option

days

func WithMaxBackups added in v0.0.7

func WithMaxBackups(maxBackups int) Option

func WithMaxSize added in v0.0.7

func WithMaxSize(maxSize int) Option

megabytes

func WithStderr added in v0.2.0

func WithStderr() Option

WithStderr enables writing logs to os.Stderr.

func WithStdout added in v0.2.0

func WithStdout() Option

WithStdout enables writing logs to os.Stdout.

func WithTraceID added in v0.1.0

func WithTraceID(on bool) Option

WithTraceID configures the logger to add `trace_id` field to structured log messages.

Directories

Path Synopsis
example
basic command
Basic usage: zero-config InitLogger (default level=info, output=stdout), runtime SetLevel, and Sync on exit.
Basic usage: zero-config InitLogger (default level=info, output=stdout), runtime SetLevel, and Sync on exit.
file command
File-only logging with rotation options.
File-only logging with rotation options.
noContext command
Non-context logging + OpenTelemetry metrics (log_total counter).
Non-context logging + OpenTelemetry metrics (log_total counter).
teeJSON command
Container-style setup: JSON logs to stdout, optionally also to a file (tee).
Container-style setup: JSON logs to stdout, optionally also to a file (tee).
withContext command
Context-aware logging with trace_id injection and auto span events.
Context-aware logging with trace_id injection and auto span events.

Jump to

Keyboard shortcuts

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