log

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 9 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package log centralises slog setup for every HB Labs service. One call from main() — log.New("service-foo") — returns the canonical per-service logger: text handler in local, JSON handler in prod, level from LOG_LEVEL, and `service` attached as a base attribute so every line carries the originating service without being threaded through call sites.

The package also wires the standard correlation chain. Once a logger is set as default via slog.SetDefault(log.New(...)), the per-request logger that httpx.RequestID puts into context inherits the service attribute; calling log.WithContext(ctx) inside a handler returns a logger pre-bound with request_id, device_id and organization_id.

Required fields per architecture.md: ts, level, service, msg, request_id, device_id, organization_id. The first four are emitted by every slog handler we build; the last three flow in via context.

Index

Constants

View Source
const (
	LevelDebug = slog.LevelDebug
	LevelInfo  = slog.LevelInfo
	LevelWarn  = slog.LevelWarn
	LevelError = slog.LevelError
)

Level constants. Re-exported so callers don't need to import log/slog just to name a level.

Variables

This section is empty.

Functions

func AssertContains

func AssertContains(t *testing.T, buf *bytes.Buffer, match string)

AssertContains is the standard assertion against a buffer returned by Capture: when match is non-empty the buffer must contain it (typically the warn substring the code under test should emit); when match is empty the buffer must be empty too — a stray log line during a "happy path" case usually means the code is logging when it shouldn't.

func Capture

func Capture(t *testing.T, service string) *bytes.Buffer

Capture swaps slog.Default() for a buffer-backed logger tagged service+"-test" and restores the previous default via t.Cleanup. The returned buffer accumulates every log line emitted while the test runs, so callers can assert on the contents after the code under test has executed.

Lives in package log (rather than a logtest subpackage) so test code reads `log.Capture(t, "envcfg")` — the import of "testing" here is harmless: the Go linker doesn't pull testing into a binary that never references it.

Captures at LevelInfo regardless of LOG_LEVEL — keeps tests hermetic; use CaptureAt to pin a different threshold.

func CaptureAt

func CaptureAt(t *testing.T, service string, level Level) *bytes.Buffer

CaptureAt is the explicit-level form of Capture. Useful when the code under test relies on a specific level threshold (e.g. an access log middleware that should skip its attribute build when the configured level is below the global default — that branch can only be exercised by pinning the default at LevelInfo while the middleware asks for LevelDebug).

func Debug

func Debug(msg string, args ...any)

Debug logs at debug level against slog.Default().

func DebugContext

func DebugContext(ctx context.Context, msg string, args ...any)

DebugContext is the ctx-aware form of Debug.

func Default

func Default() *slog.Logger

Default returns the canonical service-level *slog.Logger. After the bootstrap call slog.SetDefault(log.New("svc")) it carries the service tag and the configured handler. Exposed here so packages across the repo can fall back to "the configured app logger" without importing log/slog directly — keeping core/log as the single import that touches the underlying logger library.

func Error

func Error(msg string, args ...any)

Error logs at error level against slog.Default().

func ErrorContext

func ErrorContext(ctx context.Context, msg string, args ...any)

ErrorContext is the ctx-aware form of Error.

func Info

func Info(msg string, args ...any)

Info logs at info level against slog.Default().

func InfoContext

func InfoContext(ctx context.Context, msg string, args ...any)

InfoContext is the ctx-aware form of Info.

func LoggerFromContext

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

LoggerFromContext returns the logger attached by WithLogger, falling back to slog.Default() so callers can write LoggerFromContext(ctx).Info(...) without a nil check even when running outside an HTTP request (cron jobs, NATS consumers, tests).

func New

func New(service string) *slog.Logger

New builds the canonical *slog.Logger for a service. Format and level are read from the environment:

  • HBL_ENV: "local" defaults to text format, anything else (staging, prod, ci) defaults to JSON. Loki/Promtail ingests JSON typed without regex; we only ever drop to text on a developer laptop.
  • LOG_FORMAT: explicit override ("text" or "json"). Handy when a prod debug session wants text in `kubectl logs`.
  • LOG_LEVEL: "debug" | "info" | "warn" | "error" (case-insensitive; unknown → info).

The returned logger has `service=<service>` as a base attribute. Set it as the process default so context-bound loggers (e.g. the one httpx.RequestID puts into ctx) inherit the service tag too:

l := log.New("service-foo")
slog.SetDefault(l)

func NewHandler

func NewHandler(format string, opts *slog.HandlerOptions) slog.Handler

NewHandler returns a slog handler ready to feed slog.SetDefault. Most services should call New / NewTo instead — this exists for callers that need the handler standalone (custom slog wrappers, io.MultiWriter fan-out, fixtures).

format selects the wire format:

  • "json" → slog.JSONHandler, one JSON object per line. Loki/Promtail/Vector ingest each field typed without parsing.
  • "text" (default) → slog.TextHandler, key=value, terminal-friendly.

Anything else (including empty string) falls back to "text" so a missing env var never crashes the boot. opts is forwarded as-is to whichever handler is built; pass it to set Level, AddSource, etc.

Output goes to os.Stderr by default; use NewHandlerTo to redirect. Container runtimes expect logs on stderr — staying on the default is almost always the right call.

func NewHandlerTo

func NewHandlerTo(w io.Writer, format string, opts *slog.HandlerOptions) slog.Handler

NewHandlerTo is the explicit-writer form of NewHandler.

Always lowercases the level value (`info` instead of `INFO`) so log lines blend into the rest of the key=value text without shouting; if the caller passes its own ReplaceAttr we chain after the lowercase step so user transforms still apply.

func NewTo

func NewTo(w io.Writer, service string) *slog.Logger

NewTo is the explicit-writer variant of New. Tests use it to capture log output; production has no reason to redirect away from stderr.

func OrganizationIDFromContext

func OrganizationIDFromContext(ctx context.Context) string

OrganizationIDFromContext returns the organization-id attached to ctx, or "" if none is set. "" rather than panicking so background workers without an org context (cron jobs, platform-level NATS consumers) don't crash when reusing handler code paths.

func ParseLevel

func ParseLevel(s string) slog.Level

ParseLevel converts the strings "debug", "info", "warn", "error" (case-insensitive) into the matching slog.Level. Unknown values fall back to Info. Useful for `LOG_LEVEL=debug`-style env wiring.

func SetDefault

func SetDefault(l *slog.Logger)

SetDefault makes l the process-wide default *slog.Logger that Default() (and slog.Default()) return. Thin wrapper so service bootstraps install the canonical logger via core/log without importing log/slog just for this one call. Typical use:

l := log.New("service-foo")
log.SetDefault(l)

func Warn

func Warn(msg string, args ...any)

Warn logs at warn level against slog.Default().

func WarnContext

func WarnContext(ctx context.Context, msg string, args ...any)

WarnContext is the ctx-aware form of Warn.

func WithContext

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

WithContext returns a logger pre-bound with the correlation IDs stored in ctx by upstream middleware: request_id and device_id (httpx.RequestID), and organization_id (log.WithOrganizationID, typically called by auth after the request's org is resolved).

Resolution:

  • Base = the *slog.Logger httpx.RequestID attached to ctx, falling back to slog.Default() — which is the service-tagged logger from New if slog.SetDefault was called at boot.
  • organization_id is appended only when set, so platform-level traffic (no org) doesn't carry an empty field.

Use it at the top of any handler / NATS consumer / cron job that wants its log lines correlated with the request that triggered them:

l := log.WithContext(ctx)
l.Info("processing", "items", n)

func WithLogger

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

WithLogger attaches l to ctx for retrieval by LoggerFromContext. Lives in this package (not httpx) so core/log owns every logger-related context helper — and so httpx can import log without creating a cycle.

func WithOrganizationID

func WithOrganizationID(ctx context.Context, orgID string) context.Context

WithOrganizationID attaches orgID to ctx so subsequent WithContext loggers carry organization_id automatically. Auth middleware calls this once it resolves the session's org; the value then flows through the rest of the request (and any goroutines derived from it) without being threaded as a function argument.

Empty orgID returns ctx unchanged so callers can pipe potentially- missing values through without a nil check.

Types

type Attr

type Attr = slog.Attr

Attr is the canonical key/value attribute pair carried by log records. Aliased from slog so callers can build typed-attribute slices for LogAttrs without importing log/slog. Pair with the String/Int/Duration constructors below.

func Any

func Any(k string, v any) Attr

Any builds an Attr from a value of any type, deferring to slog's type inference. Re-export of slog.Any for the cases where the value isn't a string/int/duration (a bool, a float, a nested struct) and a typed constructor would be overkill.

func Duration

func Duration(k string, v time.Duration) Attr

Duration builds an Attr with a time.Duration value. Thin re-export of slog.Duration.

func Group

func Group(key string, args ...any) Attr

Group builds a nested Attr whose value is a sub-group of the given args (alternating key/value, same grammar as the variadic logging calls). Re-export of slog.Group so a call site can emit a structured sub-document — e.g. log.Group("client", "ip", ip, "app_version", ver) renders as client.ip / client.app_version in JSON — without importing log/slog directly.

func Int

func Int(k string, v int) Attr

Int builds an Attr with an int value. Thin re-export of slog.Int.

func String

func String(k, v string) Attr

String builds an Attr with a string value. Thin re-export of slog.String so call sites read `log.String("path", r.URL.Path)` without dragging log/slog into business code.

type Level

type Level = slog.Level

Level is the level type used when classifying log records. Aliased from slog so callers across the repo can write `log.LevelInfo` and signatures like `func(...) log.Level` without importing log/slog directly — keeping core/log as the single dependency that touches the underlying logger library.

type Logger

type Logger = slog.Logger

Logger is the canonical structured-logger type. Aliased from *slog.Logger so callers can write `*log.Logger` in signatures and receive the same value core/log builds, without importing log/slog. Methods (.With, .Info, .LogAttrs, .Enabled, …) come from slog and are called as usual on the value.

func Buffered

func Buffered() (*bytes.Buffer, *Logger)

Buffered returns a buffer + *Logger pair: every record the logger emits is captured in the buffer so tests can assert on log shape after the code under test has run. Hermetic w.r.t. LOG_LEVEL — always captures debug+ so the assertion isn't silently dropped when an env var is set in CI:

buf, lg := log.Buffered()
mw := RequestID(lg)
mw(handler).ServeHTTP(rec, req)
if !strings.Contains(buf.String(), "request_id=...") { ... }

For tests that need the process-wide default swapped (i.e. code reads via slog.Default rather than an injected logger), use Capture instead.

func Quiet

func Quiet() *Logger

Quiet returns a *Logger that drops every record. Use in tests where the code under test logs something on the path being exercised (warnings, errors) and you want the test output to stay clean — e.g. `New(Options{Logger: log.Quiet()})`. Centralised here so the io.Discard / NewTextHandler boilerplate doesn't get re-typed in every package's test file.

Jump to

Keyboard shortcuts

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