log

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2026 License: AGPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package log is Loom's centralized logging surface.

All records land in {configDir}/logs/loom.log, which is rotated once to loom.log.1 at startup when it exceeds 5 MB. Two logger families share the file:

  • Structured (slog-backed): For, InfoKV, WarnKV, ErrorKV, DebugKV. Records carry a subsystem tag plus component=daemon when emitted by the daemon child, so a single grep scopes output to a subsystem.
  • Legacy (*log.Logger): InfoLog, WarningLog, ErrorLog plus the Infof/Warnf/Errorf helpers. Retained for callers not yet migrated; routed through the same writer and gated by the same level.

Both families respect LOOM_LOG_LEVEL (debug|info|warn|error) and the --log-level CLI flag. Debug records are emitted only through the Structured logger. Every provides a minimal rate limiter for hot paths that would otherwise flood the log.

Index

Constants

View Source
const EnvLogFormat = "LOOM_LOG_FORMAT"

EnvLogFormat selects the output format for the structured logger. "json" → JSON lines; anything else → plain text. Legacy *log.Logger vars (InfoLog/WarningLog/ErrorLog) always emit plain text for source-compatibility with the ~117 existing .Printf call sites.

View Source
const EnvLogLevel = "LOOM_LOG_LEVEL"

EnvLogLevel gates the minimum log level for both the Structured logger and the legacy *log.Logger vars (InfoLog / WarningLog / ErrorLog). Values: "debug", "info" (default), "warn", "error". Legacy records below the gate are silently dropped at the writer layer so no change to the ~90 *.Printf call sites is required. `SetLevel` lets tests and future runtime toggles update the gate after Initialize.

Variables

View Source
var (
	WarningLog *log.Logger
	InfoLog    *log.Logger
	ErrorLog   *log.Logger

	// Structured is the slog-based logger preferred for new call sites
	// (see InfoKV/WarnKV/ErrorKV). It shares the log file with the
	// legacy loggers. Nil until Initialize has been called.
	Structured *slog.Logger
)

WarningLog, InfoLog, and ErrorLog are the legacy *log.Logger package-level vars used by pre-Structured call sites (about 90 Printf invocations). They share the log file with Structured and are gated by LOOM_LOG_LEVEL via the levelWriter shim so a legacy Printf at INFO tier is silently dropped under LOOM_LOG_LEVEL=warn. Nil until Initialize has been called.

Functions

func Close

func Close()

Close closes the log file.

func DebugKV

func DebugKV(msg string, kv ...any)

DebugKV emits a structured DEBUG record. Preferred for new call sites — the KV pairs survive log-shipping and stay grep-friendly.

func Debugf

func Debugf(format string, v ...any)

Debugf emits a printf-style DEBUG record via the Structured logger. Gated by LOOM_LOG_LEVEL=debug (slog short-circuits before formatting when the level is below the handler's gate, so the `fmt.Sprintf` is paid only when debug is enabled).

func ErrorKV

func ErrorKV(msg string, kv ...any)

ErrorKV emits a structured ERROR record.

func Errorf

func Errorf(format string, v ...any)

Errorf logs at ERROR level. No-op if Initialize has not been called.

func For

func For(subsystem string, kv ...any) *slog.Logger

For returns a Structured child logger tagged with subsystem=... plus any additional KV pairs. Designed to be cached on a long-lived owner (e.g. *session.Instance) so every log from that owner carries the same identifying attributes without each call site repeating them. Returns a no-op logger if Initialize has not run yet, so callers at package init time are safe.

func GetEnvWithLegacy

func GetEnvWithLegacy(current, legacy string) string

GetEnvWithLegacy returns os.Getenv(current); if empty it falls back to os.Getenv(legacy) and prints a one-time deprecation notice to stderr naming the new var to set.

func InfoKV

func InfoKV(msg string, kv ...any)

InfoKV emits a structured INFO record. Prefer this over Infof for new call sites — kv pairs survive log-shipping.

func Infof

func Infof(format string, v ...any)

Infof logs at INFO level. No-op if Initialize has not been called.

func Initialize

func Initialize(logDir string, daemon bool) error

Initialize should be called once at the beginning of the program to set up logging. defer Close() after calling this function.

logDir specifies the directory for the log file. If empty, os.TempDir() is used. When non-empty, the directory is created if it does not exist.

Returns a non-nil error when the log file could not be opened. Callers may still use the package-level loggers after an error — Initialize falls back to stderr (or io.Discard when daemon is true, for a detached child process whose parent has nil'd stdio), so the app stays functional in a degraded mode instead of crashing via panic like the previous implementation.

func LogFilePath

func LogFilePath() string

LogFilePath returns the absolute path of the log file opened by Initialize. Empty string before Initialize runs. Exposed so the `debug` subcommand can tell users where to `tail` their logs.

func LoggerFrom

func LoggerFrom(ctx context.Context) *slog.Logger

LoggerFrom returns the *slog.Logger stashed on ctx, or the package-level Structured logger as a fallback. If both are nil (e.g. before Initialize), returns a no-op logger so callers can invoke methods without a nil check.

func SetLevel

func SetLevel(l slog.Level)

SetLevel updates the Structured logger's minimum level at runtime. Safe to call before Initialize; the value is applied whenever the handler is first created.

func TraceID

func TraceID(ctx context.Context) string

TraceID returns the trace ID carried on ctx, or "" if none was minted. Safe to call with a nil context.

func WarnKV

func WarnKV(msg string, kv ...any)

WarnKV emits a structured WARNING record.

func Warnf

func Warnf(format string, v ...any)

Warnf logs at WARNING level. No-op if Initialize has not been called.

func WithLogger

func WithLogger(ctx context.Context, logger *slog.Logger) context.Context

WithLogger stashes a pre-tagged *slog.Logger on ctx. Downstream code that wants to inherit per-request attributes (subsystem, instance title, trace ID) should prefer LoggerFrom(ctx) over calling log.For(...) again.

func WithTrace

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

WithTrace mints a new trace ID, attaches it to ctx, and returns both the new context and the trace ID string. Format: `t<monotonic>-<4 hex chars>` (e.g. `t0042-a7f3`). The random suffix disambiguates IDs across process restarts where the counter resets to zero. If ctx already carries a trace ID, it is reused (so a single user action produces one trace even when multiple layers call WithTrace).

func WithValueForTrace

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

WithValueForTrace attaches an already-minted trace ID to ctx without touching the counter. Use when a trace survives across an async boundary (e.g. a scriptResumeMsg carrying the originating dispatch's trace) and the caller needs a ctx the engine can read via TraceID. Empty id yields ctx unchanged so callers do not have to pre-check.

Types

type Every

type Every struct {
	// contains filtered or unexported fields
}

Every is used to log at most once every timeout duration. Safe for concurrent use; ShouldLog takes a mutex before touching the internal timestamp.

func NewEvery

func NewEvery(timeout time.Duration) *Every

NewEvery constructs an Every rate-limiter with the given minimum spacing between ShouldLog() approvals. Use at the call site that would otherwise flood the log — e.g. a tick-based status sampler.

func (*Every) ShouldLog

func (e *Every) ShouldLog() bool

ShouldLog returns true if the timeout has passed since the last log. The first call always returns true (zero lastAt predates any real time, so Sub >= timeout holds trivially).

Jump to

Keyboard shortcuts

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