logging

package
v1.21.1 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Overview

Package logging provides zerolog construction and configuration helpers for Watchtower.

This package holds no logger state. It does not expose a global logger, Global accessor, InitLogger, or init-based setup. Callers construct a *zerolog.Logger via New and related helpers and pass it explicitly to subsystems.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidLogFormat = errors.New("invalid log format")

ErrInvalidLogFormat is returned by ConfigureWriter for unrecognized format names.

View Source
var ErrUnknownLogLevel = errors.New("unknown log level")

ErrUnknownLogLevel is returned by ParseLevel for unrecognized level strings.

Functions

func ConfigureLevel

func ConfigureLevel(log *zerolog.Logger, rawLevel, debugFlag, traceFlag string) *zerolog.Logger

ConfigureLevel applies CLI level aliases (--debug, --trace) to a zerolog logger.

Priority is traceFlag, then debugFlag, then rawLevel. When rawLevel is empty and neither alias is set, the logger is returned unchanged. Invalid rawLevel leaves the logger unchanged without returning an error.

Callers that must fail fast on a bad --log-level (for example flags.SetupLogging or composition-root wiring) must validate with ParseLevel first and surface that error. ConfigureLevel alone will not reject invalid values.

Parameters:

  • log: Logger to reconfigure.
  • rawLevel: Explicit level string from --log-level (may be empty).
  • debugFlag: Truthy when --debug is set.
  • traceFlag: Truthy when --trace is set.

Returns:

  • *zerolog.Logger: Logger with the resolved level applied.

func ConfigureWriter

func ConfigureWriter(format string, noColor bool) (io.Writer, error)

ConfigureWriter returns an io.Writer for the requested log format.

Supported formats (case-insensitive):

  • json: raw os.Stderr (zerolog default JSON encoding)
  • pretty: zerolog.ConsoleWriter with colors unless noColor is true
  • logfmt: ConsoleWriter with NoColor and key=value-style formatting
  • auto: pretty when stderr is a TTY, NO_COLOR is not present in the environment (presence includes empty value), and noColor is false. Otherwise logfmt is used.

Parameters:

  • format: Requested format name (json, pretty, logfmt, or auto).
  • noColor: When true, disables colorized pretty output.

Returns:

  • io.Writer: Writer suitable for zerolog.New.
  • error: Non-nil when format is not recognized.

func LogNotifierInfo

func LogNotifierInfo(log *zerolog.Logger, notifierNames []string)

LogNotifierInfo logs details about the notification setup for Watchtower.

It reports the list of configured notifier names (for example "email, slack") or indicates that no notifications are set up.

Parameters:

  • log: The zerolog logger used to write the notification information.
  • notifierNames: Names of configured notifiers.

func LogScheduleInfo

func LogScheduleInfo(log *zerolog.Logger, info ScheduleInfo)

LogScheduleInfo logs information about the scheduling or run mode configuration.

It handles scheduled runs with timing details, one-time updates, or indicates no periodic runs, ensuring users understand when and how updates will occur. It also warns about flag conflicts such as when both run-once and update-on-start are enabled.

Parameters:

  • log: The zerolog logger used to write the schedule information.
  • info: Resolved schedule and mode values (no flag reads).

func LogfmtWriter

func LogfmtWriter(out io.Writer) zerolog.ConsoleWriter

LogfmtWriter returns a ConsoleWriter that emits logfmt-style lines to out.

Intended for tests and any caller that wants logfmt on a custom sink.

Parameters:

  • out: Destination for formatted log lines.

Returns:

  • zerolog.ConsoleWriter: Logfmt-style console writer writing to out.

func New

func New(w io.Writer, level Level) *zerolog.Logger

New creates a *zerolog.Logger configured with the given writer and level.

The logger always includes timestamps on events.

Parameters:

  • w: Destination for log output.
  • level: Minimum level of events to emit.

Returns:

  • *zerolog.Logger: Configured logger instance.

func NewTestLogger

func NewTestLogger(level Level) (*zerolog.Logger, *bytes.Buffer)

NewTestLogger constructs a *zerolog.Logger writing logfmt lines to a buffer.

Level maps via the same Level constants as New.

Parameters:

  • level: Minimum level of events to capture.

Returns:

  • *zerolog.Logger: Logger writing to the returned buffer.
  • *bytes.Buffer: Buffer containing captured log output.

func NopLogger

func NopLogger() *zerolog.Logger

NopLogger returns a discarded *zerolog.Logger for tests that do not assert on logs.

Returns:

  • *zerolog.Logger: Logger that discards all events.

func ParseLevel

func ParseLevel(level string) (zerolog.Level, error)

ParseLevel maps a CLI level string to zerolog.Level.

Accepted values (case-insensitive) are panic, fatal, error, warn, warning, info, debug, and trace.

Parameters:

  • level: Level name string (may include surrounding whitespace).

Returns:

  • zerolog.Level: Parsed level, or NoLevel when invalid.
  • error: Non-nil when the level string is not recognized.

func SetupStartupLogger

func SetupStartupLogger(log *zerolog.Logger, notifier types.Notifier) *zerolog.Logger

SetupStartupLogger prepares the logger for startup messages and starts notifier batching.

Callers that suppress startup messages must return before invoking this helper. When notifier is non-nil, StartNotification batches subsequent startup lines for a single SendNotification.

Parameters:

  • log: The zerolog logger used for startup messages.
  • notifier: The notification system instance for batching messages, or nil.

Returns:

  • *zerolog.Logger: The logger to use for writing startup messages.

func With

func With(log *zerolog.Logger, key string, val any) *zerolog.Logger

With returns a child logger with a single field added.

The returned logger is a new instance (immutable style). Prefer native zerolog event chaining at call sites (log.Debug().Str(...).Msg(...)) when attaching fields for a single log line. Use With or WithFields when building a scoped child logger that is reused across multiple statements.

Parameters:

  • log: Parent logger.
  • key: Field name.
  • val: Field value.

Returns:

  • *zerolog.Logger: Child logger with the field applied.

func WithError

func WithError(log *zerolog.Logger, err error) *zerolog.Logger

WithError returns a child logger with the error field added when err is non-nil.

When err is nil, the original logger is returned unchanged. Prefer log.Debug().Err(err).Msg(...) (or the appropriate level) for a single log line.

Parameters:

  • log: Parent logger.
  • err: Error to attach, or nil.

Returns:

  • *zerolog.Logger: Child logger with error field, or log unchanged when err is nil.

func WithFields

func WithFields(log *zerolog.Logger, fields map[string]any) *zerolog.Logger

WithFields returns a child logger with all fields added.

The returned logger is a new instance (immutable style). Prefer log.With().Fields(fields).Logger() or per-event Fields when that reads more clearly. WithFields remains available for shared scoped loggers.

Parameters:

  • log: Parent logger.
  • fields: Map of field names to values.

Returns:

  • *zerolog.Logger: Child logger with all fields applied.

func WriteStartupMessage

func WriteStartupMessage(params StartupParams)

WriteStartupMessage logs or notifies startup information from resolved configuration.

It reports Watchtower's version, notification setup, container filtering details, scheduling information, and HTTP API status. Callers that suppress startup messages set NoStartupMessage and return without requiring Logger.

Parameters:

  • params: Resolved startup messaging inputs from config.Load (no CLI flag reads). When NoStartupMessage is false, Logger must be non-nil and should be the hooked process logger (after Notifier.RegisterHook) so batching captures startup lines.

Types

type APIVersionProvider

type APIVersionProvider interface {
	GetVersion() string
}

APIVersionProvider reports the Docker API version for startup messaging.

Defined here (rather than depending on pkg/container.Client) so this package stays free of container→flags import cycles when flags configures logging.

type Level

type Level uint8

Level maps to zerolog levels.

const (
	TraceLevel Level = iota
	DebugLevel
	InfoLevel
	WarnLevel
	ErrorLevel
	FatalLevel
	PanicLevel
)

Logging levels ordered from most to least verbose.

type ScheduleInfo

type ScheduleInfo struct {
	// RunOnce indicates a single update run then exit.
	RunOnce bool
	// UpdateOnStart is the effective update-on-start value, or nil when unset or false.
	UpdateOnStart *bool
	// HTTPAPIUpdate is true when the HTTP update API is enabled.
	HTTPAPIUpdate bool
	// HTTPAPIPeriodicPolls is true when scheduled polls run with the HTTP API.
	HTTPAPIPeriodicPolls bool
	// Sched is the time of the first scheduled run, or zero if none.
	Sched time.Time
}

ScheduleInfo holds resolved schedule and mode values for startup schedule messaging.

Values come from config.Load projections rather than CLI flag reads.

type StartupParams

type StartupParams struct {
	// ScheduleInfo holds run-once, update-on-start, HTTP API, and next-run schedule values.
	ScheduleInfo

	// Logger is the zerolog logger used for startup messages. Required when NoStartupMessage is false.
	Logger *zerolog.Logger
	// NoStartupMessage suppresses all startup logs and notifications when true.
	NoStartupMessage bool
	// Filtering is a human-readable description of the container filter.
	Filtering string
	// Scope is the operational scope name, or empty when unset.
	Scope string
	// Client is the Docker client used for API version reporting.
	Client APIVersionProvider
	// Notifier sends batched startup messages when not suppressed.
	Notifier types.Notifier
	// Version is the Watchtower version string.
	Version string
}

StartupParams holds resolved process values for startup messaging.

Callers must populate these from config.Load output. Do not read CLI flags here. Schedule and mode fields live on the embedded ScheduleInfo (single source of truth).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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