1 Home
Virgil edited this page 2026-03-11 12:07:25 +00:00

go-log

Module: forge.lthn.ai/core/go-log

Structured logging and error handling for Core applications. Provides levelled logging with key-value pairs, structured error types with operation context, and combined log-and-return helpers. Foundation dependency for most Core packages.

Architecture

File Purpose
log.go Logger struct, log levels, default logger, package-level functions
errors.go Err structured error, E(), Wrap(), WrapCode(), error introspection

Key Types

Logger

  • Logger — Structured logger: Debug(), Info(), Warn(), Error(), Security()
  • LevelLevelQuiet, LevelError, LevelWarn, LevelInfo, LevelDebug
  • OptionsLevel, Output (io.Writer), Rotation, RedactKeys
  • RotationOptionsFilename, MaxSize (MB), MaxAge (days), MaxBackups, Compress

Logger methods: SetLevel(), SetOutput(), SetRedactKeys().

Customisable style functions: StyleTimestamp, StyleDebug, StyleInfo, StyleWarn, StyleError, StyleSecurity.

Structured Errors

  • ErrOp string (operation), Msg string, Err error (underlying), Code string (machine-readable)
  • Implements error and Unwrap() for errors.Is()/errors.As() chain support

Error Creation

Function Description
E(op, msg, err) Create error with operation context
Wrap(err, op, msg) Wrap error (returns nil if err is nil, preserves Code)
WrapCode(err, code, op, msg) Wrap with error code
NewCode(code, msg) Sentinel error with code (no underlying error)

Error Introspection

Function Description
Op(err) Extract operation name from error chain
ErrCode(err) Extract error code
Message(err) Extract message
Root(err) Root cause (deepest unwrap)
AllOps(err) Iterator over all operations in chain
StackTrace(err) Slice of operation names
FormatStackTrace(err) Formatted: "op1 -> op2 -> op3"

Combined Log-and-Return

Function Description
LogError(err, op, msg) Log at Error + return wrapped error
LogWarn(err, op, msg) Log at Warn + return wrapped error
Must(err, op, msg) Log at Error + panic if err != nil

Standard Library Wrappers

Is(), As(), NewError(), Join() — Convenience wrappers around errors package.

Usage

import "forge.lthn.ai/core/go-log"

// Package-level logging
log.SetLevel(log.LevelDebug)
log.Info("server started", "port", 8080)
log.Error("connection failed", "err", err)
log.Security("unauthorised access attempt", "ip", clientIP)

// Structured errors
return log.E("db.Query", "failed to fetch user", err)
return log.Wrap(err, "api.Handler", "request failed")
return log.WrapCode(err, "VALIDATION_ERROR", "user.Create", "invalid email")

// Combined log-and-return
return log.LogError(err, "service.Start", "failed to initialise")

// Custom logger
logger := log.New(log.Options{
    Level:      log.LevelDebug,
    RedactKeys: []string{"password", "token"},
})

Dependencies

  • Zero external dependencies (only stdlib + testify for tests)
  • Username() helper reads current system username