log

package
v0.47.8 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package log provides structured logging for bosun using zerolog. It supports both human-readable console output for CLI commands and JSON output for daemon mode and log aggregation.

Index

Constants

View Source
const (
	// FieldComponent identifies the subsystem (daemon, reconcile, git, deploy).
	FieldComponent = "component"

	// FieldRequestID is the HTTP request correlation ID.
	FieldRequestID = "request_id"

	// FieldReconcileID is the reconcile run correlation ID.
	FieldReconcileID = "reconcile_id"

	// FieldSource identifies the trigger source (webhook, poll, manual).
	FieldSource = "source"

	// FieldDurationMS is the operation duration in milliseconds.
	FieldDurationMS = "duration_ms"

	// FieldError contains the error message.
	FieldError = "error"

	// FieldOperation identifies the current operation.
	FieldOperation = "operation"

	// FieldTarget identifies the deployment target.
	FieldTarget = "target"

	// FieldPath is a file or directory path.
	FieldPath = "path"

	// FieldCommit is a git commit hash.
	FieldCommit = "commit"

	// FieldBranch is a git branch name.
	FieldBranch = "branch"

	// FieldContainer is a container name.
	FieldContainer = "container"

	// FieldMethod is an HTTP method.
	FieldMethod = "method"

	// FieldURL is an HTTP URL or path.
	FieldURL = "url"

	// FieldStatus is an HTTP status code.
	FieldStatus = "status"

	// FieldRemoteAddr is the observed peer address of an HTTP connection.
	// This is a fact: it comes from the connection, not from a header.
	FieldRemoteAddr = "remote_addr"

	// FieldForwardedFor is a client address claimed by an X-Forwarded-For
	// header, recorded only when the observed peer is a trusted proxy.
	// This is a claim, not a fact -- keep it in its own field so the two are
	// never confused. See internal/daemon.forwardedForClient.
	FieldForwardedFor = "forwarded_for"
)

Standard field names for structured logging.

View Source
const (
	ComponentDaemon    = "daemon"
	ComponentReconcile = "reconcile"
	ComponentGit       = "git"
	ComponentDeploy    = "deploy"
	ComponentSOPS      = "sops"
	ComponentTemplate  = "template"
	ComponentDocker    = "docker"
	ComponentManifest  = "manifest"
	ComponentWebhook   = "webhook"
	ComponentHTTP      = "http"
	ComponentTunnel    = "tunnel"
)

Component values for FieldComponent.

View Source
const (
	SourceWebhook       = "webhook"
	SourcePoll          = "poll"
	SourceManual        = "manual"
	SourceStartup       = "startup"
	SourceGitHub        = "github"
	SourceGitLab        = "gitlab"
	SourceGitea         = "gitea"
	SourceDriftSelfHeal = "drift-self-heal"
)

Source values for FieldSource.

View Source
const (
	DebugLevel = zerolog.DebugLevel
	InfoLevel  = zerolog.InfoLevel
	WarnLevel  = zerolog.WarnLevel
	ErrorLevel = zerolog.ErrorLevel
)

Log levels.

Variables

This section is empty.

Functions

func Component

func Component(component string) zerolog.Logger

Component returns a logger with the component field set. Use this for code paths without a context (CLI commands, package init). When a context.Context is available, prefer ComponentCtx.

func ComponentCtx added in v0.14.0

func ComponentCtx(ctx context.Context, component string) zerolog.Logger

ComponentCtx returns a logger from context with the component field added. If an enriched logger was previously stashed on the context via WithContext, the returned logger inherits its fields (e.g. correlation IDs). For code paths without context (CLI commands, init), use Component instead.

func Ctx

func Ctx(ctx context.Context) *zerolog.Logger

Ctx returns a logger from the context, or the global logger if none exists. This is the primary way to get a context-aware logger.

func Debug

func Debug() *zerolog.Event

Debug starts a debug-level log event.

func DurationMS

func DurationMS(start time.Time) int64

DurationMS calculates and returns the duration in milliseconds from a start time.

func EnableDaemonMode added in v0.40.7

func EnableDaemonMode()

EnableDaemonMode marks the process as a daemon and rebuilds the logger using daemon-aware auto-detection. Explicit format and level choices, the primary output, and additional writers remain intact across the rebuild.

func Error

func Error() *zerolog.Event

Error starts an error-level log event.

func Fatal

func Fatal() *zerolog.Event

Fatal starts a fatal-level log event. After logging, the process will exit with status 1.

func FromContext

func FromContext(ctx context.Context) zerolog.Logger

FromContext creates a logger from the global logger with request_id and reconcile_id read from raw context values. It intentionally rebuilds from scratch rather than reading the stashed zerolog.Logger, which avoids zerolog's append-only key duplication when called in loops (e.g. coalesced reconcile iterations). Only FieldRequestID and FieldReconcileID are propagated; no other stashed logger fields survive the rebuild.

func Info

func Info() *zerolog.Event

Info starts an info-level log event.

func Init

func Init(opts *Options)

Init initializes the global logger with the given options. If options is nil, environment variables and auto-detection are used.

func Logger

func Logger() *zerolog.Logger

Logger returns the global logger.

func NewReconcileContext

func NewReconcileContext(ctx context.Context) (context.Context, string)

NewReconcileContext creates a new context with a reconcile ID and returns both the context and the ID.

func NewRequestContext

func NewRequestContext(ctx context.Context) (context.Context, string)

NewRequestContext creates a new context with a request ID and returns both the context and the ID.

func ReconcileIDFromContext

func ReconcileIDFromContext(ctx context.Context) string

ReconcileIDFromContext retrieves the reconcile ID from context. Returns empty string if not present.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext retrieves the request ID from context. Returns empty string if not present.

func SanitizeForOutput added in v0.44.5

func SanitizeForOutput(s string) string

SanitizeForOutput strips the runes that let untrusted text forge or visually rewrite an operator-facing line: Unicode control characters (newline, carriage return, ESC and the rest of C0/C1, so neither a fake log record nor an ANSI escape survives), format characters (Cf — zero-width joiners and the bidirectional overrides), and the line and paragraph separators. Spaces and printable Unicode survive unchanged, and invalid UTF-8 decodes to U+FFFD instead of reaching the sink as raw bytes.

The result is uncapped; callers bound length themselves, either with SanitizeForOutputCapped or with their own cap applied to the return value. It lives in this package rather than in a caller because both internal/daemon (webhook attribution) and internal/reconcile (container health output) need it, and daemon already imports reconcile — a helper in either of them would be an import cycle for the other.

func SanitizeForOutputCapped added in v0.44.5

func SanitizeForOutputCapped(s string, maxRunes int) string

SanitizeForOutputCapped sanitizes as SanitizeForOutput does and keeps at most maxRunes of the surviving code points. Stripped runes do not count against the cap. A negative maxRunes means no cap; zero returns the empty string.

func SetGlobalLevel

func SetGlobalLevel(level Level)

SetGlobalLevel sets the minimum log level.

func Warn

func Warn() *zerolog.Event

Warn starts a warn-level log event.

func With

func With() zerolog.Context

With creates a child logger with additional context.

func WithContext

func WithContext(ctx context.Context, l *zerolog.Logger) context.Context

WithContext returns a new context with the logger attached.

func WithDuration

func WithDuration(e *zerolog.Event, start time.Time) *zerolog.Event

WithDuration adds a duration_ms field to a log event.

func WithError

func WithError(e *zerolog.Event, err error) *zerolog.Event

WithError adds an error field to a log event.

func WithReconcileID

func WithReconcileID(ctx context.Context, id string) context.Context

WithReconcileID adds a reconcile run ID to the context. If id is empty, a new UUID is generated.

func WithRequestID

func WithRequestID(ctx context.Context, id string) context.Context

WithRequestID adds a request ID to the context. If id is empty, a new UUID is generated.

Types

type Format

type Format string

Format specifies the log output format.

const (
	// FormatAuto automatically detects the best format based on environment.
	FormatAuto Format = "auto"
	// FormatConsole outputs human-readable colored logs.
	FormatConsole Format = "console"
	// FormatJSON outputs structured JSON logs.
	FormatJSON Format = "json"
)

func GetFormat

func GetFormat() Format

GetFormat returns the current log format.

type Level

type Level = zerolog.Level

Level wraps zerolog.Level for external use.

func GetLevel

func GetLevel() Level

GetLevel returns the current log level.

type Options

type Options struct {
	Format   Format
	Level    Level
	LevelSet bool // Explicitly set level (needed because Level 0 is TraceLevel)

	// Output replaces stdout as the primary log destination when non-nil.
	Output io.Writer

	// AdditionalWriters are extra io.Writers that receive log output alongside
	// the primary writer (Output, or stdout when Output is nil). Used by the
	// Sentry integration to fan out logs without changing existing call sites.
	AdditionalWriters []io.Writer
}

Options configures the logger.

Jump to

Keyboard shortcuts

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