Compare commits

..

14 commits

Author SHA1 Message Date
Virgil
f19e3e383e fix(log): inherit nested error codes
Some checks failed
CI / auto-fix (push) Failing after 1s
CI / test (push) Failing after 3s
CI / auto-merge (push) Failing after 0s
2026-04-01 09:49:40 +00:00
Virgil
000bd46649 Align log helpers with RFC logging behavior
Some checks failed
CI / auto-fix (push) Failing after 0s
CI / test (push) Failing after 2s
CI / auto-merge (push) Failing after 0s
2026-04-01 08:58:37 +00:00
Virgil
8b97c833ff fix(log): make redaction key matching exact
Some checks failed
CI / test (push) Failing after 2s
CI / auto-fix (push) Failing after 0s
CI / auto-merge (push) Failing after 0s
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-01 05:08:41 +00:00
Virgil
282b7242ec fix(log): stop inheriting codes in wrapcode helpers
Some checks failed
CI / test (push) Failing after 3s
CI / auto-fix (push) Failing after 1s
CI / auto-merge (push) Failing after 1s
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-01 04:55:55 +00:00
Virgil
e2481552b5 fix(log): surface nested recovery metadata
Some checks failed
CI / test (push) Failing after 2s
CI / auto-fix (push) Failing after 0s
CI / auto-merge (push) Failing after 0s
Co-Authored-By: Virgil <virgil@lethean.io>
2026-04-01 04:41:48 +00:00
Virgil
f72c8daf3b refactor(ax): align recovery helpers with AX docs
Some checks failed
CI / test (push) Failing after 2s
CI / auto-fix (push) Failing after 0s
CI / auto-merge (push) Failing after 0s
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-30 13:36:30 +00:00
Virgil
7205e913bb feat: add agent-oriented recovery metadata to errors
Some checks failed
CI / test (push) Failing after 2s
CI / auto-fix (push) Failing after 1s
CI / auto-merge (push) Failing after 1s
2026-03-30 06:33:30 +00:00
Virgil
3962cb7ac3 refactor(ax): complete logger docs and safe-default regression coverage
Some checks failed
CI / test (push) Failing after 2s
CI / auto-fix (push) Failing after 1s
CI / auto-merge (push) Failing after 1s
2026-03-30 05:27:49 +00:00
Virgil
6b6f025be7 refactor(ax): finish AX docs pass and test naming alignment
Some checks failed
CI / test (push) Failing after 2s
CI / auto-fix (push) Failing after 0s
CI / auto-merge (push) Failing after 0s
2026-03-30 00:36:24 +00:00
Virgil
d7c46d9482 Add RFC for exported log package API
Some checks failed
CI / auto-fix (push) Failing after 0s
CI / test (push) Failing after 2s
CI / auto-merge (push) Failing after 1s
2026-03-30 00:15:09 +00:00
Claude
a543af9cc6 refactor(ax): AX compliance pass — usage example comments on all exported functions
- Add usage example comments to Logger methods (SetLevel, Level, SetOutput, SetRedactKeys, Debug, Info, Warn, Error, Security)
- Add usage example comments to error introspection (Op, ErrCode, Root, AllOps, StackTrace, FormatStackTrace)
- Add usage example comments to package-level functions (Default, SetDefault)
- Banned imports (fmt, io, os, errors) are LEGITIMATE — this IS the logging/error abstraction layer

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 00:15:08 +00:00
Virgil
4f7e730802 fix(log): sanitise structured logging keys and values
Some checks failed
CI / test (push) Failing after 2s
CI / auto-fix (push) Failing after 0s
CI / auto-merge (push) Failing after 1s
2026-03-29 23:29:43 +00:00
Virgil
355af66a5c fix(log): normalise levels, preserve nested error codes, and sanitise log messages
Some checks failed
CI / auto-fix (push) Failing after 0s
CI / test (push) Failing after 3s
CI / auto-merge (push) Failing after 0s
2026-03-29 22:39:46 +00:00
Virgil
3ed9ea71dc fix(log): harden logger defaults and default proxy safety 2026-03-29 22:35:38 +00:00
12 changed files with 1362 additions and 1188 deletions

View file

@ -1,61 +0,0 @@
# Security Attack Vector Mapping
- `CLAUDE.md` reviewed.
- `CODEX.md` was not present in this repository.
- Scope: exported API entry points that accept caller-controlled data, plus direct OS/environment reads. Public field-based inputs (`Logger.Style*`, `Err.Op`, `Err.Msg`, `Err.Err`, `Err.Code`) are called out in the relevant rows because they are consumed by methods rather than setter functions.
- Common sink: `(*Logger).log` in `log.go:169`-`242` writes the final log line with `fmt.Fprintf(output, "%s %s %s%s\n", ...)` at `log.go:242`.
- Existing controls in the common sink: string values in `keyvals` are `%q`-escaped at `log.go:234`-`236`, exact-match redaction is applied with `slices.Contains(redactKeys, keyStr)` at `log.go:227`-`231`, and `Err`-derived `op` / `stack` context is auto-added at `log.go:178`-`211`.
- Gaps in the common sink: `msg`, key names, `error` values, and other non-string values are formatted without sanitisation at `log.go:221`-`242`.
## Logger Configuration And Emission
| Function | File:Line | Input source | Flows into | Current validation | Potential attack vector |
| --- | --- | --- | --- | --- | --- |
| `New(opts Options)` | `log.go:111` | Caller-controlled `Options.Level`, `Options.Output`, `Options.Rotation`, `Options.RedactKeys`; optional global `RotationWriterFactory` | Initial `Logger` state; `opts.Output` or `RotationWriterFactory(*opts.Rotation)` becomes `Logger.output`; `RedactKeys` copied into `Logger.redactKeys` and later checked during logging | Falls back to `os.Stderr` if output is `nil`; only uses rotation when `Rotation != nil`, `Filename != ""`, and `RotationWriterFactory != nil`; `RedactKeys` slice is cloned | Path-based write/exfiltration if untrusted `Rotation.Filename` reaches a permissive factory; arbitrary side effects or exfiltration through a caller-supplied writer; log suppression if an untrusted config sets `LevelQuiet`; redaction bypass if secret keys do not exactly match configured names |
| `(*Logger).SetLevel(level Level)` | `log.go:136` | Caller-controlled log level | `Logger.level`, then `shouldLog()` in all log methods | None | Audit bypass or loss of forensic detail if attacker-controlled config lowers the level or uses unexpected numeric values |
| `(*Logger).SetOutput(w io.Writer)` | `log.go:150` | Caller-controlled writer | `Logger.output`, then `fmt.Fprintf` in `log.go:242` | None | Log exfiltration, unexpected side effects in custom writers, or panic/DoS if a nil or broken writer is installed |
| `(*Logger).SetRedactKeys(keys ...string)` | `log.go:157` | Caller-controlled key names | `Logger.redactKeys`, then `slices.Contains(redactKeys, keyStr)` during formatting | Slice clone only | Secret leakage when caller omits aliases, case variants, or confusable keys; CPU overhead grows linearly with large redact lists |
| `(*Logger).Debug(msg string, keyvals ...any)` | `log.go:246` | Caller-controlled `msg`, `keyvals`, and mutable `Logger.StyleDebug` field | `StyleDebug("[DBG]")` -> `(*Logger).log` -> `fmt.Fprintf` | Level gate only; string `keyvals` values are quoted; exact-match redaction for configured keys; no nil check on `StyleDebug` | Log forging or parser confusion via unsanitised `msg`, key names, `error` strings, or non-string `fmt.Stringer` values; secret leakage in `msg` or non-redacted fields; nil style function can panic |
| `(*Logger).Info(msg string, keyvals ...any)` | `log.go:253` | Caller-controlled `msg`, `keyvals`, and mutable `Logger.StyleInfo` field | `StyleInfo("[INF]")` -> `(*Logger).log` -> `fmt.Fprintf` | Same controls as `Debug` | Same attack surface as `Debug`: log injection, secret leakage outside exact-key redaction, and nil-style panic/DoS |
| `(*Logger).Warn(msg string, keyvals ...any)` | `log.go:260` | Caller-controlled `msg`, `keyvals`, and mutable `Logger.StyleWarn` field | `StyleWarn("[WRN]")` -> `(*Logger).log` -> `fmt.Fprintf` | Same controls as `Debug` | Same attack surface as `Debug`: log injection, secret leakage outside exact-key redaction, and nil-style panic/DoS |
| `(*Logger).Error(msg string, keyvals ...any)` | `log.go:267` | Caller-controlled `msg`, `keyvals`, and mutable `Logger.StyleError` field | `StyleError("[ERR]")` -> `(*Logger).log` -> `fmt.Fprintf` | Same controls as `Debug` | Same attack surface as `Debug`; higher impact because error logs are more likely to be consumed by SIEMs and incident tooling |
| `(*Logger).Security(msg string, keyvals ...any)` | `log.go:276` | Caller-controlled `msg`, `keyvals`, and mutable `Logger.StyleSecurity` field | `StyleSecurity("[SEC]")` -> `(*Logger).log` -> `fmt.Fprintf` | Uses `LevelError` threshold so security events still emit when normal info logging is disabled; otherwise same controls as `Debug` | Spoofed or injected security events if untrusted text reaches `msg` / `keyvals`; secret leakage in high-signal security logs; nil-style panic/DoS |
| `Username()` | `log.go:284` | OS account lookup from `user.Current()` and environment variables `USER` / `USERNAME` | Returned username string to caller | Uses `user.Current()` first; falls back to `USER`, then `USERNAME`; no normalisation or escaping | Username spoofing in untrusted/containerised environments where env vars are attacker-controlled; downstream log/UI injection if callers print the returned value without escaping |
| `SetDefault(l *Logger)` | `log.go:305` | Caller-controlled logger pointer and its mutable fields (`output`, `Style*`, redact config, level) | Global `defaultLogger`, then all package-level log functions plus `LogError`, `LogWarn`, and `Must` | None | Nil logger causes later panic/DoS; swapping the default logger can redirect logs, disable redaction, or install panicking style/output hooks globally |
| `SetLevel(level Level)` | `log.go:310` | Caller-controlled log level | `defaultLogger.SetLevel(level)` | None beyond instance setter behaviour | Same as `(*Logger).SetLevel`, but process-global |
| `SetRedactKeys(keys ...string)` | `log.go:315` | Caller-controlled redact keys | `defaultLogger.SetRedactKeys(keys...)` | None beyond instance setter behaviour | Same as `(*Logger).SetRedactKeys`, but process-global |
| `Debug(msg string, keyvals ...any)` | `log.go:320` | Caller-controlled `msg` and `keyvals` routed through the global logger | `defaultLogger.Debug(...)` -> `(*Logger).log` -> `fmt.Fprintf` | Same controls as `(*Logger).Debug`; additionally depends on `defaultLogger` not being nil | Same as `(*Logger).Debug`, plus global DoS if `defaultLogger` was set to nil |
| `Info(msg string, keyvals ...any)` | `log.go:325` | Caller-controlled `msg` and `keyvals` routed through the global logger | `defaultLogger.Info(...)` -> `(*Logger).log` -> `fmt.Fprintf` | Same controls as `(*Logger).Info`; additionally depends on `defaultLogger` not being nil | Same as `(*Logger).Info`, plus global DoS if `defaultLogger` was set to nil |
| `Warn(msg string, keyvals ...any)` | `log.go:330` | Caller-controlled `msg` and `keyvals` routed through the global logger | `defaultLogger.Warn(...)` -> `(*Logger).log` -> `fmt.Fprintf` | Same controls as `(*Logger).Warn`; additionally depends on `defaultLogger` not being nil | Same as `(*Logger).Warn`, plus global DoS if `defaultLogger` was set to nil |
| `Error(msg string, keyvals ...any)` | `log.go:335` | Caller-controlled `msg` and `keyvals` routed through the global logger | `defaultLogger.Error(...)` -> `(*Logger).log` -> `fmt.Fprintf` | Same controls as `(*Logger).Error`; additionally depends on `defaultLogger` not being nil | Same as `(*Logger).Error`, plus global DoS if `defaultLogger` was set to nil |
| `Security(msg string, keyvals ...any)` | `log.go:340` | Caller-controlled `msg` and `keyvals` routed through the global logger | `defaultLogger.Security(...)` -> `(*Logger).log` -> `fmt.Fprintf` | Same controls as `(*Logger).Security`; additionally depends on `defaultLogger` not being nil | Same as `(*Logger).Security`, plus global DoS if `defaultLogger` was set to nil |
## Error Construction And Emission
| Function | File:Line | Input source | Flows into | Current validation | Potential attack vector |
| --- | --- | --- | --- | --- | --- |
| `(*Err).Error()` | `errors.go:25` | Public `Err.Op`, `Err.Msg`, `Err.Err`, and `Err.Code` fields, including direct struct literal construction by callers | Returned error string via `fmt.Sprintf`; if the error is later logged as a non-string value, the text reaches `(*Logger).log` -> `fmt.Fprintf` | None | Log injection or response spoofing via attacker-controlled op/message/code text; secret disclosure via underlying error text; machine-readable code spoofing |
| `E(op, msg string, err error)` | `errors.go:56` | Caller-controlled `op`, `msg`, `err` | New `Err` instance, then `(*Err).Error()` when rendered | None | Same as `(*Err).Error()`: attacker-controlled context and underlying error text can be surfaced in logs or responses |
| `Wrap(err error, op, msg string)` | `errors.go:67` | Caller-controlled `err`, `op`, `msg` | New `Err` wrapper; preserves existing `Code` from wrapped `*Err` if present | Returns `nil` when `err == nil`; preserves code if wrapped error is an `*Err` | Untrusted wrapped errors can carry misleading `Code` / `Op` context forward; op/msg text is not sanitised before later logging or presentation |
| `WrapCode(err error, code, op, msg string)` | `errors.go:86` | Caller-controlled `err`, `code`, `op`, `msg` | New `Err` with explicit code, then `(*Err).Error()` when rendered | Returns `nil` only when both `err == nil` and `code == ""` | Error-code spoofing; untrusted message/op text can be pushed into logs or external error responses |
| `NewCode(code, msg string)` | `errors.go:99` | Caller-controlled `code`, `msg` | New `Err` with no underlying error | None | Same as `WrapCode` without an underlying cause: spoofed codes and unsanitised user-facing text |
| `NewError(text string)` | `errors.go:119` | Caller-controlled text | `errors.New(text)` return value, then any downstream logging or response handling | None | Log / response injection or sensitive text disclosure when callers pass untrusted strings through as raw errors |
| `Join(errs ...error)` | `errors.go:125` | Caller-controlled error list | `errors.Join(errs...)`, then downstream `Error()` / logging | Standard library behaviour only | Size amplification and multi-message disclosure if attacker-controlled errors are aggregated and later surfaced verbatim |
| `LogError(err error, op, msg string)` | `errors.go:235` | Caller-controlled `err`, `op`, `msg`; global `defaultLogger` state | `Wrap(err, op, msg)` return value plus `defaultLogger.Error(msg, "op", op, "err", err)` -> `fmt.Fprintf` | Returns `nil` when `err == nil`; otherwise inherits logger controls (quoted string values, exact-key redaction) | Log injection through `msg`, `op`, or `err.Error()`; sensitive error disclosure; global DoS/exfiltration if `defaultLogger` was replaced or nil |
| `LogWarn(err error, op, msg string)` | `errors.go:250` | Caller-controlled `err`, `op`, `msg`; global `defaultLogger` state | `Wrap(err, op, msg)` return value plus `defaultLogger.Warn(msg, "op", op, "err", err)` -> `fmt.Fprintf` | Returns `nil` when `err == nil`; otherwise inherits logger controls | Same as `LogError`, with the additional risk that warnings may be treated as non-critical and reviewed less carefully |
| `Must(err error, op, msg string)` | `errors.go:265` | Caller-controlled `err`, `op`, `msg`; global `defaultLogger` state | `defaultLogger.Error(msg, "op", op, "err", err)` -> `fmt.Fprintf`, then `panic(Wrap(err, op, msg))` | Only executes when `err != nil`; otherwise same logger controls as `LogError` | Attacker-triggerable panic/DoS if external input can force the error path; same log injection and disclosure risks as `LogError` before the panic |
## Error Inspection Helpers
| Function | File:Line | Input source | Flows into | Current validation | Potential attack vector |
| --- | --- | --- | --- | --- | --- |
| `(*Err).Unwrap()` | `errors.go:43` | Public `Err.Err` field | Returned underlying error | None | No direct sink in this package; risk comes from whatever the wrapped error does when callers continue processing it |
| `Is(err, target error)` | `errors.go:107` | Caller-controlled `err`, `target` | `errors.Is(err, target)` return value | Standard library behaviour only | Minimal direct attack surface here; any custom `Is` semantics come from attacker-supplied error implementations |
| `As(err error, target any)` | `errors.go:113` | Caller-controlled `err`, `target` | `errors.As(err, target)` return value | No wrapper-side validation of `target` | Invalid `target` values can panic through `errors.As`, creating an application-level DoS if misuse is reachable |
| `Op(err error)` | `errors.go:133` | Caller-controlled error chain | Extracted `Err.Op` string | Type-check via `errors.As`; otherwise none | Spoofed operation names if callers trust attacker-controlled `*Err` values for audit, metrics, or access decisions |
| `ErrCode(err error)` | `errors.go:143` | Caller-controlled error chain | Extracted `Err.Code` string | Type-check via `errors.As`; otherwise none | Spoofed machine-readable error codes if callers trust attacker-controlled wrapped errors |
| `Message(err error)` | `errors.go:153` | Caller-controlled error chain | Extracted `Err.Msg` or `err.Error()` string | Returns `""` for `nil`; otherwise none | Unsanitised attacker-controlled message text can be re-used in logs, UIs, or API responses |
| `Root(err error)` | `errors.go:166` | Caller-controlled error chain | Returned deepest unwrapped error | Returns `nil` for `nil`; otherwise none | Minimal direct sink, but can expose a sensitive root error that callers later surface verbatim |
| `AllOps(err error)` | `errors.go:181` | Caller-controlled error chain | Iterator over all `Err.Op` values | Traverses `errors.Unwrap` chain; ignores non-`*Err` nodes | Long attacker-controlled wrap chains can increase CPU work; extracted op strings remain unsanitised |
| `StackTrace(err error)` | `errors.go:198` | Caller-controlled error chain | `[]string` of operation names | None beyond `AllOps` traversal | Memory growth proportional to chain length; untrusted op strings may later be logged or displayed |
| `FormatStackTrace(err error)` | `errors.go:207` | Caller-controlled error chain | Joined stack string via `strings.Join(ops, " -> ")` | Returns `""` when no ops are found; otherwise none | Log / UI injection if untrusted op names are later rendered without escaping; size amplification for deep chains |

View file

@ -1,89 +0,0 @@
---
title: API Contract
description: Exported API surface for dappco.re/go/core/log
---
# API Contract
This page enumerates the exported API surface of `dappco.re/go/core/log`.
`Test coverage` means there is an explicit test in `log_test.go` or
`errors_test.go` that directly exercises the item. Indirect coverage through a
different exported API is marked `no`.
## Types
| Name | Signature | Package Path | Description | Test Coverage |
|------|-----------|--------------|-------------|---------------|
| `Err` | `type Err struct { Op string; Msg string; Err error; Code string }` | `dappco.re/go/core/log` | Structured error with operation context, message, wrapped cause, and optional machine-readable code. | yes |
| `Level` | `type Level int` | `dappco.re/go/core/log` | Logging verbosity enum ordered from quiet to debug. | yes |
| `Logger` | `type Logger struct { StyleTimestamp func(string) string; StyleDebug func(string) string; StyleInfo func(string) string; StyleWarn func(string) string; StyleError func(string) string; StyleSecurity func(string) string; /* unexported fields */ }` | `dappco.re/go/core/log` | Concurrent-safe structured logger with overridable style hooks. | yes |
| `Options` | `type Options struct { Level Level; Output io.Writer; Rotation *RotationOptions; RedactKeys []string }` | `dappco.re/go/core/log` | Logger construction options for level, destination, rotation, and redaction. | yes |
| `RotationOptions` | `type RotationOptions struct { Filename string; MaxSize int; MaxAge int; MaxBackups int; Compress bool }` | `dappco.re/go/core/log` | Log rotation and retention policy passed to the rotation writer factory. | yes |
## Constants
| Name | Signature | Package Path | Description | Test Coverage |
|------|-----------|--------------|-------------|---------------|
| `LevelQuiet` | `const LevelQuiet Level = iota` | `dappco.re/go/core/log` | Suppresses all log output. | yes |
| `LevelError` | `const LevelError Level` | `dappco.re/go/core/log` | Emits only error and security messages. | yes |
| `LevelWarn` | `const LevelWarn Level` | `dappco.re/go/core/log` | Emits warnings, errors, and security messages. | yes |
| `LevelInfo` | `const LevelInfo Level` | `dappco.re/go/core/log` | Emits informational, warning, error, and security messages. | yes |
| `LevelDebug` | `const LevelDebug Level` | `dappco.re/go/core/log` | Emits all log levels, including debug details. | yes |
## Variable
| Name | Signature | Package Path | Description | Test Coverage |
|------|-----------|--------------|-------------|---------------|
| `RotationWriterFactory` | `var RotationWriterFactory func(RotationOptions) io.WriteCloser` | `dappco.re/go/core/log` | Optional injection point for creating rotating log writers. | yes |
## Methods
| Name | Signature | Package Path | Description | Test Coverage |
|------|-----------|--------------|-------------|---------------|
| `(*Err).Error` | `func (e *Err) Error() string` | `dappco.re/go/core/log` | Formats an `Err` into its public error string representation. | yes |
| `(*Err).Unwrap` | `func (e *Err) Unwrap() error` | `dappco.re/go/core/log` | Returns the wrapped cause for `errors.Is` and `errors.As`. | yes |
| `(Level).String` | `func (l Level) String() string` | `dappco.re/go/core/log` | Returns the canonical lowercase name for a log level. | yes |
| `(*Logger).SetLevel` | `func (l *Logger) SetLevel(level Level)` | `dappco.re/go/core/log` | Updates the logger's active verbosity threshold. | yes |
| `(*Logger).Level` | `func (l *Logger) Level() Level` | `dappco.re/go/core/log` | Returns the logger's current verbosity threshold. | yes |
| `(*Logger).SetOutput` | `func (l *Logger) SetOutput(w io.Writer)` | `dappco.re/go/core/log` | Replaces the logger's output writer. | yes |
| `(*Logger).SetRedactKeys` | `func (l *Logger) SetRedactKeys(keys ...string)` | `dappco.re/go/core/log` | Replaces the set of keys whose values are redacted in output. | yes |
| `(*Logger).Debug` | `func (l *Logger) Debug(msg string, keyvals ...any)` | `dappco.re/go/core/log` | Emits a debug log line when the logger level allows it. | yes |
| `(*Logger).Info` | `func (l *Logger) Info(msg string, keyvals ...any)` | `dappco.re/go/core/log` | Emits an informational log line when the logger level allows it. | yes |
| `(*Logger).Warn` | `func (l *Logger) Warn(msg string, keyvals ...any)` | `dappco.re/go/core/log` | Emits a warning log line when the logger level allows it. | yes |
| `(*Logger).Error` | `func (l *Logger) Error(msg string, keyvals ...any)` | `dappco.re/go/core/log` | Emits an error log line when the logger level allows it. | yes |
| `(*Logger).Security` | `func (l *Logger) Security(msg string, keyvals ...any)` | `dappco.re/go/core/log` | Emits a security log line using the security prefix at error visibility. | yes |
## Functions
| Name | Signature | Package Path | Description | Test Coverage |
|------|-----------|--------------|-------------|---------------|
| `New` | `func New(opts Options) *Logger` | `dappco.re/go/core/log` | Constructs a logger from the supplied options and defaults. | yes |
| `Username` | `func Username() string` | `dappco.re/go/core/log` | Returns the current system username with environment fallbacks. | yes |
| `Default` | `func Default() *Logger` | `dappco.re/go/core/log` | Returns the package-level default logger. | yes |
| `SetDefault` | `func SetDefault(l *Logger)` | `dappco.re/go/core/log` | Replaces the package-level default logger. | yes |
| `SetLevel` | `func SetLevel(level Level)` | `dappco.re/go/core/log` | Updates the package-level default logger's level. | yes |
| `SetRedactKeys` | `func SetRedactKeys(keys ...string)` | `dappco.re/go/core/log` | Updates the package-level default logger's redaction keys. | yes |
| `Debug` | `func Debug(msg string, keyvals ...any)` | `dappco.re/go/core/log` | Proxies a debug log call to the default logger. | yes |
| `Info` | `func Info(msg string, keyvals ...any)` | `dappco.re/go/core/log` | Proxies an informational log call to the default logger. | yes |
| `Warn` | `func Warn(msg string, keyvals ...any)` | `dappco.re/go/core/log` | Proxies a warning log call to the default logger. | yes |
| `Error` | `func Error(msg string, keyvals ...any)` | `dappco.re/go/core/log` | Proxies an error log call to the default logger. | yes |
| `Security` | `func Security(msg string, keyvals ...any)` | `dappco.re/go/core/log` | Proxies a security log call to the default logger. | yes |
| `E` | `func E(op, msg string, err error) error` | `dappco.re/go/core/log` | Creates an `*Err` with operation context and an optional wrapped cause. | yes |
| `Wrap` | `func Wrap(err error, op, msg string) error` | `dappco.re/go/core/log` | Wraps an error with operation context and preserves any existing code. | yes |
| `WrapCode` | `func WrapCode(err error, code, op, msg string) error` | `dappco.re/go/core/log` | Wraps an error with operation context and an explicit machine-readable code. | yes |
| `NewCode` | `func NewCode(code, msg string) error` | `dappco.re/go/core/log` | Creates a coded error without an underlying cause. | yes |
| `Is` | `func Is(err, target error) bool` | `dappco.re/go/core/log` | Convenience wrapper around `errors.Is`. | yes |
| `As` | `func As(err error, target any) bool` | `dappco.re/go/core/log` | Convenience wrapper around `errors.As`. | yes |
| `NewError` | `func NewError(text string) error` | `dappco.re/go/core/log` | Convenience wrapper around `errors.New`. | yes |
| `Join` | `func Join(errs ...error) error` | `dappco.re/go/core/log` | Convenience wrapper around `errors.Join`. | yes |
| `Op` | `func Op(err error) string` | `dappco.re/go/core/log` | Extracts the outermost operation name from an `*Err`. | yes |
| `ErrCode` | `func ErrCode(err error) string` | `dappco.re/go/core/log` | Extracts the machine-readable code from an `*Err`. | yes |
| `Message` | `func Message(err error) string` | `dappco.re/go/core/log` | Returns an `*Err` message or falls back to `err.Error()`. | yes |
| `Root` | `func Root(err error) error` | `dappco.re/go/core/log` | Returns the deepest wrapped cause in an error chain. | yes |
| `AllOps` | `func AllOps(err error) iter.Seq[string]` | `dappco.re/go/core/log` | Returns an iterator over every non-empty operation in an error chain. | no |
| `StackTrace` | `func StackTrace(err error) []string` | `dappco.re/go/core/log` | Collects the logical stack trace of operations from an error chain. | yes |
| `FormatStackTrace` | `func FormatStackTrace(err error) string` | `dappco.re/go/core/log` | Formats the logical stack trace as a single `outer -> inner` string. | yes |
| `LogError` | `func LogError(err error, op, msg string) error` | `dappco.re/go/core/log` | Logs at error level and returns the wrapped error. | yes |
| `LogWarn` | `func LogWarn(err error, op, msg string) error` | `dappco.re/go/core/log` | Logs at warning level and returns the wrapped error. | yes |
| `Must` | `func Must(err error, op, msg string)` | `dappco.re/go/core/log` | Logs and panics when given a non-nil error. | yes |

View file

@ -63,6 +63,9 @@ type Err struct {
Msg string // human-readable description
Err error // underlying cause (optional)
Code string // machine-readable code (optional, e.g. "VALIDATION_FAILED")
Retryable bool // whether the caller can retry the operation
RetryAfter *time.Duration // optional retry delay hint
NextAction string // suggested next step when not retryable
}
```
@ -115,6 +118,9 @@ log(LevelInfo, "[INF]", ...)
| if any value implements `error`:
| extract Op -> append "op" key if not already present
| extract FormatStackTrace -> append "stack" key if not already present
| extract recovery hints -> append "retryable",
| "retry_after_seconds",
| "next_action" if not already present
+-- format key-value pairs:
| string values -> %q (quoted, injection-safe)
| other values -> %v

View file

@ -1,74 +0,0 @@
# Convention Drift Audit
Date: 2026-03-23
## Scope
- `CODEX.md` was not present anywhere under `/workspace` on 2026-03-23.
- This audit used `CLAUDE.md` as the available convention source.
- The `stdlib→core.*` bucket is interpreted here as explicit stdlib wording and non-`dappco.re/go/core/*` path references that still look pre-migration.
## Missing SPDX Headers
- `CLAUDE.md:1`
- `errors.go:1`
- `errors_test.go:1`
- `log.go:1`
- `log_test.go:1`
- `docs/index.md:1`
- `docs/development.md:1`
- `docs/architecture.md:1`
## stdlib→core.* Drift
- `CLAUDE.md:33` still describes `Is`, `As`, and `Join` as `stdlib wrappers`.
- `log.go:107` still references `core/go-io` rather than a `dappco.re/go/core/*` path.
- `docs/index.md:8` still uses the old module path `forge.lthn.ai/core/go-log`.
- `docs/index.md:18` still imports `forge.lthn.ai/core/go-log`.
- `docs/index.md:81` still describes runtime dependencies as `Go standard library only`.
- `docs/index.md:86` still references `core/go-io`.
- `docs/index.md:92` still lists the module path as `forge.lthn.ai/core/go-log`.
- `docs/index.md:95` still says `iter.Seq` comes from `the standard library`.
- `docs/development.md:10` still says `iter.Seq` comes from `the standard library`.
- `docs/development.md:126` still says `prefer the standard library`.
- `docs/architecture.md:217` still references `core/go-io`.
## UK English Drift
- `errors.go:264` uses `Initialize()` in an example comment.
- `log_test.go:179` uses `unauthorized access`.
- `log_test.go:185` asserts on `unauthorized access`.
- `errors_test.go:309` uses `initialization failed`.
## Missing Tests
- `errors.go:186` has no test for the `AllOps` early-stop path when the iterator consumer returns `false`.
- `log.go:289` has no test coverage for `Username()` falling back to `USER`.
- `log.go:292` has no test coverage for `Username()` falling back to `USERNAME` after `USER` is empty.
Coverage note: `go test -coverprofile=cover.out ./...` reports `97.7%` statement coverage; these are the only uncovered code paths in the current package.
## Missing Usage-Example Comments
Interpretation: public entry points without an inline `Example:` block in their doc comment, especially where peer APIs in `errors.go` already include examples.
- `log.go:71` `RotationOptions`
- `log.go:94` `Options`
- `log.go:108` `RotationWriterFactory`
- `log.go:111` `New`
- `log.go:157` `(*Logger).SetRedactKeys`
- `log.go:276` `(*Logger).Security`
- `log.go:284` `Username`
- `log.go:300` `Default`
- `log.go:305` `SetDefault`
- `errors.go:107` `Is`
- `errors.go:113` `As`
- `errors.go:119` `NewError`
- `errors.go:125` `Join`
- `errors.go:133` `Op`
- `errors.go:143` `ErrCode`
- `errors.go:153` `Message`
- `errors.go:166` `Root`
- `errors.go:181` `AllOps`
- `errors.go:198` `StackTrace`
- `errors.go:207` `FormatStackTrace`

View file

@ -5,7 +5,7 @@ description: Structured logging and error handling for Core applications
# go-log
`forge.lthn.ai/core/go-log` provides structured logging and contextual error
`dappco.re/go/core/log` provides structured logging and contextual error
handling for Go applications built on the Core framework. It is a small,
zero-dependency library (only `testify` at test time) that replaces ad-hoc
`fmt.Println` / `log.Printf` calls with level-filtered, key-value structured
@ -15,7 +15,7 @@ stack.
## Quick Start
```go
import "forge.lthn.ai/core/go-log"
import "dappco.re/go/core/log"
// Use the package-level default logger straight away
log.SetLevel(log.LevelDebug)
@ -54,6 +54,10 @@ log.Op(err) // "user.Save"
log.Root(err) // the original underlyingErr
log.StackTrace(err) // ["user.Save", "db.Connect"]
log.FormatStackTrace(err) // "user.Save -> db.Connect"
// Recovery hints are also available when the error carries them
log.IsRetryable(err) // false unless a wrapped Err marks it retryable
log.RecoveryAction(err) // "retry with backoff" when provided
```
### Combined Log-and-Return
@ -70,7 +74,7 @@ if err != nil {
| File | Purpose |
|------|---------|
| `log.go` | Logger type, log levels, key-value formatting, redaction, default logger, `Username()` helper |
| `errors.go` | `Err` structured error type, creation helpers (`E`, `Wrap`, `WrapCode`, `NewCode`), introspection (`Op`, `ErrCode`, `Root`, `StackTrace`), combined log-and-return helpers (`LogError`, `LogWarn`, `Must`) |
| `errors.go` | `Err` structured error type, creation helpers (`E`, `Wrap`, `WrapCode`, `NewCode`, and recovery-aware variants), introspection (`Op`, `ErrCode`, `Root`, `StackTrace`, recovery hints), combined log-and-return helpers (`LogError`, `LogWarn`, `Must`) |
| `log_test.go` | Tests for the Logger: level filtering, key-value output, redaction, injection prevention, security logging |
| `errors_test.go` | Tests for structured errors: creation, wrapping, code propagation, introspection, stack traces, log-and-return helpers |
@ -89,7 +93,7 @@ code.
## Module Path
```
forge.lthn.ai/core/go-log
dappco.re/go/core/log
```
Requires **Go 1.26+** (uses `iter.Seq` from the standard library).

237
errors.go
View file

@ -6,9 +6,10 @@
package log
import (
"dappco.re/go/core"
"errors"
"iter"
"strings"
"time"
)
// Err represents a structured error with operational context.
@ -18,24 +19,44 @@ type Err struct {
Msg string // Human-readable message
Err error // Underlying error (optional)
Code string // Error code (optional, e.g., "VALIDATION_FAILED")
// Retryable indicates whether the caller can safely retry this error.
Retryable bool
// RetryAfter suggests a delay before retrying when Retryable is true.
RetryAfter *time.Duration
// NextAction suggests an alternative path when this error is not directly retryable.
NextAction string
}
// Error implements the error interface.
func (e *Err) Error() string {
var prefix string
if e.Op != "" {
prefix = e.Op + ": "
if e == nil {
return ""
}
if e.Err != nil {
body := e.Msg
if body == "" {
if e.Code != "" {
return core.Sprintf("%s%s [%s]: %v", prefix, e.Msg, e.Code, e.Err)
body = "[" + e.Code + "]"
}
return core.Sprintf("%s%s: %v", prefix, e.Msg, e.Err)
} else if e.Code != "" {
body += " [" + e.Code + "]"
}
if e.Code != "" {
return core.Sprintf("%s%s [%s]", prefix, e.Msg, e.Code)
if e.Err != nil {
if body != "" {
body += ": " + e.Err.Error()
} else {
body = e.Err.Error()
}
}
return core.Sprintf("%s%s", prefix, e.Msg)
if e.Op != "" {
if body != "" {
return e.Op + ": " + body
}
return e.Op
}
return body
}
// Unwrap returns the underlying error for use with errors.Is and errors.As.
@ -56,6 +77,22 @@ func E(op, msg string, err error) error {
return &Err{Op: op, Msg: msg, Err: err}
}
// EWithRecovery creates a new Err with operation context and recovery metadata.
//
// return log.EWithRecovery("api.Call", "temporary failure", err, true, &retryAfter, "retry with backoff")
func EWithRecovery(op, msg string, err error, retryable bool, retryAfter *time.Duration, nextAction string) error {
recoveryErr := &Err{
Op: op,
Msg: msg,
Err: err,
}
inheritRecovery(recoveryErr, err)
recoveryErr.Retryable = retryable
recoveryErr.RetryAfter = retryAfter
recoveryErr.NextAction = nextAction
return recoveryErr
}
// Wrap wraps an error with operation context.
// Returns nil if err is nil, to support conditional wrapping.
// Preserves error Code if the wrapped error is an *Err.
@ -67,12 +104,29 @@ func Wrap(err error, op, msg string) error {
if err == nil {
return nil
}
// Preserve Code from wrapped *Err
var typedError *Err
if As(err, &typedError) && typedError.Code != "" {
return &Err{Op: op, Msg: msg, Err: err, Code: typedError.Code}
wrapped := &Err{Op: op, Msg: msg, Err: err, Code: inheritedCode(err)}
inheritRecovery(wrapped, err)
return wrapped
}
// WrapWithRecovery wraps an error with operation context and explicit recovery metadata.
//
// return log.WrapWithRecovery(err, "api.Call", "temporary failure", true, &retryAfter, "retry with backoff")
func WrapWithRecovery(err error, op, msg string, retryable bool, retryAfter *time.Duration, nextAction string) error {
if err == nil {
return nil
}
return &Err{Op: op, Msg: msg, Err: err}
recoveryErr := &Err{
Op: op,
Msg: msg,
Err: err,
Code: ErrCode(err),
}
inheritRecovery(recoveryErr, err)
recoveryErr.Retryable = retryable
recoveryErr.RetryAfter = retryAfter
recoveryErr.NextAction = nextAction
return recoveryErr
}
// WrapCode wraps an error with operation context and error code.
@ -86,7 +140,29 @@ func WrapCode(err error, code, op, msg string) error {
if err == nil && code == "" {
return nil
}
return &Err{Op: op, Msg: msg, Err: err, Code: code}
wrapped := &Err{Op: op, Msg: msg, Err: err, Code: code}
inheritRecovery(wrapped, err)
return wrapped
}
// WrapCodeWithRecovery wraps an error with operation context, code, and recovery metadata.
//
// return log.WrapCodeWithRecovery(err, "TEMPORARY_UNAVAILABLE", "api.Call", "temporary failure", true, &retryAfter, "retry with backoff")
func WrapCodeWithRecovery(err error, code, op, msg string, retryable bool, retryAfter *time.Duration, nextAction string) error {
if err == nil && code == "" {
return nil
}
recoveryErr := &Err{
Op: op,
Msg: msg,
Err: err,
Code: code,
}
inheritRecovery(recoveryErr, err)
recoveryErr.Retryable = retryable
recoveryErr.RetryAfter = retryAfter
recoveryErr.NextAction = nextAction
return recoveryErr
}
// NewCode creates an error with just code and message (no underlying error).
@ -99,33 +175,121 @@ func NewCode(code, msg string) error {
return &Err{Msg: msg, Code: code}
}
// NewCodeWithRecovery creates a coded error with recovery metadata.
//
// var ErrTemporary = log.NewCodeWithRecovery("TEMPORARY_UNAVAILABLE", "temporary failure", true, &retryAfter, "retry with backoff")
func NewCodeWithRecovery(code, msg string, retryable bool, retryAfter *time.Duration, nextAction string) error {
return &Err{
Msg: msg,
Code: code,
Retryable: retryable,
RetryAfter: retryAfter,
NextAction: nextAction,
}
}
// inheritRecovery copies recovery metadata from the first *Err in err's chain.
func inheritRecovery(dst *Err, err error) {
if err == nil || dst == nil {
return
}
var source *Err
if As(err, &source) {
dst.Retryable = source.Retryable
dst.RetryAfter = source.RetryAfter
dst.NextAction = source.NextAction
}
}
// inheritedCode returns the first non-empty code found in an error chain.
func inheritedCode(err error) string {
for err != nil {
if wrapped, ok := err.(*Err); ok && wrapped.Code != "" {
return wrapped.Code
}
err = errors.Unwrap(err)
}
return ""
}
// RetryAfter returns the first retry-after hint from an error chain, if present.
//
// retryAfter, ok := log.RetryAfter(err)
func RetryAfter(err error) (*time.Duration, bool) {
for err != nil {
if wrapped, ok := err.(*Err); ok && wrapped.RetryAfter != nil {
return wrapped.RetryAfter, true
}
err = errors.Unwrap(err)
}
return nil, false
}
// IsRetryable reports whether the error chain contains a retryable Err.
//
// if log.IsRetryable(err) { /* retry the operation */ }
func IsRetryable(err error) bool {
var wrapped *Err
if As(err, &wrapped) {
return wrapped.Retryable
}
return false
}
// RecoveryAction returns the first next action from an error chain.
//
// next := log.RecoveryAction(err)
func RecoveryAction(err error) string {
for err != nil {
if wrapped, ok := err.(*Err); ok && wrapped.NextAction != "" {
return wrapped.NextAction
}
err = errors.Unwrap(err)
}
return ""
}
func retryableHint(err error) bool {
for err != nil {
if wrapped, ok := err.(*Err); ok && wrapped.Retryable {
return true
}
err = errors.Unwrap(err)
}
return false
}
// --- Standard Library Wrappers ---
// Is reports whether any error in err's tree matches target.
// Wrapper around errors.Is for convenience.
//
// if log.Is(err, ErrNotFound) { /* handle */ }
// if log.Is(err, context.DeadlineExceeded) { /* handle timeout */ }
func Is(err, target error) bool {
return errors.Is(err, target)
}
// As finds the first error in err's tree that matches target.
// Wrapper around errors.As for convenience.
//
// var typedError *log.Err
// if log.As(err, &typedError) { code := typedError.Code }
// var e *log.Err
// if log.As(err, &e) { /* use e.Code */ }
func As(err error, target any) bool {
return errors.As(err, target)
}
// NewError creates a simple error with the given text.
// Wrapper around errors.New for convenience.
//
// var ErrNotFound = log.NewError("not found")
// return log.NewError("invalid state")
func NewError(text string) error {
return errors.New(text)
}
// Join combines multiple errors into one.
// Wrapper around errors.Join for convenience.
//
// return log.Join(validationErr, permissionErr)
// return log.Join(validateErr, persistErr)
func Join(errs ...error) error {
return errors.Join(errs...)
}
@ -137,9 +301,9 @@ func Join(errs ...error) error {
//
// op := log.Op(err) // e.g. "user.Save"
func Op(err error) string {
var typedError *Err
if As(err, &typedError) {
return typedError.Op
var e *Err
if As(err, &e) {
return e.Op
}
return ""
}
@ -149,9 +313,9 @@ func Op(err error) string {
//
// code := log.ErrCode(err) // e.g. "VALIDATION_FAILED"
func ErrCode(err error) string {
var typedError *Err
if As(err, &typedError) {
return typedError.Code
var e *Err
if As(err, &e) {
return e.Code
}
return ""
}
@ -159,14 +323,14 @@ func ErrCode(err error) string {
// Message extracts the message from an error.
// Returns the error's Error() string if not an *Err.
//
// msg := log.Message(err) // "rate limited" (not the full "api.Call: rate limited: ...")
// msg := log.Message(err)
func Message(err error) string {
if err == nil {
return ""
}
var typedError *Err
if As(err, &typedError) {
return typedError.Msg
var e *Err
if As(err, &e) {
return e.Msg
}
return err.Error()
}
@ -230,7 +394,7 @@ func FormatStackTrace(err error) string {
if len(ops) == 0 {
return ""
}
return core.Join(" -> ", ops...)
return strings.Join(ops, " -> ")
}
// --- Combined Log-and-Return Helpers ---
@ -255,7 +419,7 @@ func LogError(err error, op, msg string) error {
return nil
}
wrapped := Wrap(err, op, msg)
defaultLogger.Error(msg, "op", op, "err", err)
Default().Error(msg, "op", op, "err", err)
return wrapped
}
@ -270,7 +434,7 @@ func LogWarn(err error, op, msg string) error {
return nil
}
wrapped := Wrap(err, op, msg)
defaultLogger.Warn(msg, "op", op, "err", err)
Default().Warn(msg, "op", op, "err", err)
return wrapped
}
@ -282,7 +446,8 @@ func LogWarn(err error, op, msg string) error {
// log.Must(Initialize(), "app", "startup failed")
func Must(err error, op, msg string) {
if err != nil {
defaultLogger.Error(msg, "op", op, "err", err)
panic(Wrap(err, op, msg))
wrapped := Wrap(err, op, msg)
Default().Error(msg, "op", op, "err", err)
panic(wrapped)
}
}

View file

@ -2,34 +2,37 @@ package log
import (
"bytes"
"dappco.re/go/core"
"errors"
"fmt"
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
// --- Err type ---
// --- Err Type Tests ---
func TestErrors_ErrError_Good(t *testing.T) {
// Op + Msg + underlying error
func TestErr_Error_Good(t *testing.T) {
// With underlying error
err := &Err{Op: "db.Query", Msg: "failed to query", Err: errors.New("connection refused")}
assert.Equal(t, "db.Query: failed to query: connection refused", err.Error())
}
func TestErrors_ErrError_Bad(t *testing.T) {
// Code included in message
err := &Err{Op: "api.Call", Msg: "request failed", Code: "TIMEOUT"}
// With code
err = &Err{Op: "api.Call", Msg: "request failed", Code: "TIMEOUT"}
assert.Equal(t, "api.Call: request failed [TIMEOUT]", err.Error())
// All three: Op, Msg, Code, and underlying error
// With both underlying error and code
err = &Err{Op: "user.Save", Msg: "save failed", Err: errors.New("duplicate key"), Code: "DUPLICATE"}
assert.Equal(t, "user.Save: save failed [DUPLICATE]: duplicate key", err.Error())
// Just op and msg
err = &Err{Op: "cache.Get", Msg: "miss"}
assert.Equal(t, "cache.Get: miss", err.Error())
}
func TestErrors_ErrError_Ugly(t *testing.T) {
// No Op — no leading colon
func TestErr_Error_EmptyOp_Good(t *testing.T) {
// No Op - should not have leading colon
err := &Err{Msg: "just a message"}
assert.Equal(t, "just a message", err.Error())
@ -37,18 +40,26 @@ func TestErrors_ErrError_Ugly(t *testing.T) {
err = &Err{Msg: "error with code", Code: "ERR_CODE"}
assert.Equal(t, "error with code [ERR_CODE]", err.Error())
// No Op with underlying error only
// No Op with underlying error
err = &Err{Msg: "wrapped", Err: errors.New("underlying")}
assert.Equal(t, "wrapped: underlying", err.Error())
// Just op and msg, no error and no code
err = &Err{Op: "cache.Get", Msg: "miss"}
assert.Equal(t, "cache.Get: miss", err.Error())
}
// --- Err.Unwrap ---
func TestErr_Error_EmptyMsg_Good(t *testing.T) {
err := &Err{Op: "api.Call", Code: "TIMEOUT"}
assert.Equal(t, "api.Call: [TIMEOUT]", err.Error())
func TestErrors_ErrUnwrap_Good(t *testing.T) {
err = &Err{Op: "api.Call", Err: errors.New("underlying")}
assert.Equal(t, "api.Call: underlying", err.Error())
err = &Err{Op: "api.Call", Code: "TIMEOUT", Err: errors.New("underlying")}
assert.Equal(t, "api.Call: [TIMEOUT]: underlying", err.Error())
err = &Err{Op: "api.Call"}
assert.Equal(t, "api.Call", err.Error())
}
func TestErr_Unwrap_Good(t *testing.T) {
underlying := errors.New("underlying error")
err := &Err{Op: "test", Msg: "wrapped", Err: underlying}
@ -56,50 +67,42 @@ func TestErrors_ErrUnwrap_Good(t *testing.T) {
assert.True(t, errors.Is(err, underlying))
}
func TestErrors_ErrUnwrap_Bad(t *testing.T) {
// No underlying error — Unwrap returns nil
err := &Err{Op: "op", Msg: "no cause"}
assert.Nil(t, errors.Unwrap(err))
}
// --- Error Creation Function Tests ---
func TestErrors_ErrUnwrap_Ugly(t *testing.T) {
// Deeply nested — errors.Is still traverses the chain
root := errors.New("root")
level1 := &Err{Op: "l1", Msg: "level1", Err: root}
level2 := &Err{Op: "l2", Msg: "level2", Err: level1}
assert.True(t, errors.Is(level2, root))
}
// --- E ---
func TestErrors_E_Good(t *testing.T) {
func TestE_Good(t *testing.T) {
underlying := errors.New("base error")
err := E("op.Name", "something failed", underlying)
assert.NotNil(t, err)
var typedError *Err
assert.True(t, errors.As(err, &typedError))
assert.Equal(t, "op.Name", typedError.Op)
assert.Equal(t, "something failed", typedError.Msg)
assert.Equal(t, underlying, typedError.Err)
var logErr *Err
assert.True(t, errors.As(err, &logErr))
assert.Equal(t, "op.Name", logErr.Op)
assert.Equal(t, "something failed", logErr.Msg)
assert.Equal(t, underlying, logErr.Err)
}
func TestErrors_E_Bad(t *testing.T) {
// E with nil underlying error still creates an error
func TestE_Good_NilError(t *testing.T) {
// E creates an error even with nil underlying - useful for errors without causes
err := E("op.Name", "message", nil)
assert.NotNil(t, err)
assert.Equal(t, "op.Name: message", err.Error())
}
func TestErrors_E_Ugly(t *testing.T) {
// E with empty op produces no leading colon
err := E("", "bare message", nil)
assert.Equal(t, "bare message", err.Error())
func TestEWithRecovery_Good(t *testing.T) {
retryAfter := time.Second * 5
err := EWithRecovery("op.Name", "message", nil, true, &retryAfter, "retry once")
var logErr *Err
assert.NotNil(t, err)
assert.True(t, As(err, &logErr))
assert.True(t, logErr.Retryable)
if assert.NotNil(t, logErr.RetryAfter) {
assert.Equal(t, retryAfter, *logErr.RetryAfter)
}
assert.Equal(t, "retry once", logErr.NextAction)
}
// --- Wrap ---
func TestErrors_Wrap_Good(t *testing.T) {
func TestWrap_Good(t *testing.T) {
underlying := errors.New("base")
err := Wrap(underlying, "handler.Process", "processing failed")
@ -109,15 +112,11 @@ func TestErrors_Wrap_Good(t *testing.T) {
assert.True(t, errors.Is(err, underlying))
}
func TestErrors_Wrap_Bad(t *testing.T) {
// Wrap nil returns nil
err := Wrap(nil, "op", "msg")
assert.Nil(t, err)
}
func TestErrors_Wrap_Ugly(t *testing.T) {
// Wrap preserves Code from the inner *Err
func TestWrap_PreservesCode_Good(t *testing.T) {
// Create an error with a code
inner := WrapCode(errors.New("base"), "VALIDATION_ERROR", "inner.Op", "validation failed")
// Wrap it - should preserve the code
outer := Wrap(inner, "outer.Op", "outer context")
assert.NotNil(t, outer)
@ -125,135 +124,152 @@ func TestErrors_Wrap_Ugly(t *testing.T) {
assert.Contains(t, outer.Error(), "[VALIDATION_ERROR]")
}
// --- WrapCode ---
func TestWrap_PreservesCode_FromNestedErrWithEmptyOuterCode_Good(t *testing.T) {
inner := WrapCode(errors.New("base"), "VALIDATION_ERROR", "inner.Op", "validation failed")
mid := &Err{Op: "mid.Op", Msg: "mid failed", Err: inner}
func TestErrors_WrapCode_Good(t *testing.T) {
outer := Wrap(mid, "outer.Op", "outer context")
assert.NotNil(t, outer)
assert.Equal(t, "VALIDATION_ERROR", ErrCode(outer))
assert.Contains(t, outer.Error(), "[VALIDATION_ERROR]")
}
func TestWrap_PreservesRecovery_Good(t *testing.T) {
retryAfter := 15 * time.Second
inner := &Err{Msg: "inner", Retryable: true, RetryAfter: &retryAfter, NextAction: "inspect input"}
outer := Wrap(inner, "outer.Op", "outer context")
assert.NotNil(t, outer)
var logErr *Err
assert.True(t, As(outer, &logErr))
assert.True(t, logErr.Retryable)
if assert.NotNil(t, logErr.RetryAfter) {
assert.Equal(t, retryAfter, *logErr.RetryAfter)
}
assert.Equal(t, "inspect input", logErr.NextAction)
}
func TestWrap_PreservesCode_FromNestedChain_Good(t *testing.T) {
root := WrapCode(errors.New("base"), "CHAIN_ERROR", "inner", "inner failed")
wrapped := Wrap(fmt.Errorf("mid layer: %w", root), "outer", "outer context")
assert.Equal(t, "CHAIN_ERROR", ErrCode(wrapped))
assert.Contains(t, wrapped.Error(), "[CHAIN_ERROR]")
}
func TestWrap_NilError_Good(t *testing.T) {
err := Wrap(nil, "op", "msg")
assert.Nil(t, err)
}
func TestWrapCode_Good(t *testing.T) {
underlying := errors.New("validation failed")
err := WrapCode(underlying, "INVALID_INPUT", "api.Validate", "bad request")
assert.NotNil(t, err)
var typedError *Err
assert.True(t, errors.As(err, &typedError))
assert.Equal(t, "INVALID_INPUT", typedError.Code)
assert.Equal(t, "api.Validate", typedError.Op)
var logErr *Err
assert.True(t, errors.As(err, &logErr))
assert.Equal(t, "INVALID_INPUT", logErr.Code)
assert.Equal(t, "api.Validate", logErr.Op)
assert.Contains(t, err.Error(), "[INVALID_INPUT]")
}
func TestErrors_WrapCode_Bad(t *testing.T) {
// nil error but with code still creates an error
func TestWrapCode_Good_EmptyCodeDoesNotInherit(t *testing.T) {
inner := WrapCode(errors.New("base"), "INNER_CODE", "inner.Op", "inner failed")
outer := WrapCode(inner, "", "outer.Op", "outer failed")
var logErr *Err
assert.True(t, As(outer, &logErr))
assert.Equal(t, "", logErr.Code)
}
func TestWrapCodeWithRecovery_Good(t *testing.T) {
retryAfter := time.Minute
err := WrapCodeWithRecovery(errors.New("validation failed"), "INVALID_INPUT", "api.Validate", "bad request", true, &retryAfter, "retry with backoff")
var logErr *Err
assert.NotNil(t, err)
assert.True(t, As(err, &logErr))
assert.True(t, logErr.Retryable)
assert.NotNil(t, logErr.RetryAfter)
assert.Equal(t, retryAfter, *logErr.RetryAfter)
assert.Equal(t, "retry with backoff", logErr.NextAction)
assert.Equal(t, "INVALID_INPUT", logErr.Code)
}
func TestWrapCodeWithRecovery_Good_EmptyCodeDoesNotInherit(t *testing.T) {
retryAfter := time.Minute
inner := WrapCodeWithRecovery(errors.New("validation failed"), "INNER_CODE", "inner.Op", "inner failed", true, &retryAfter, "retry later")
outer := WrapCodeWithRecovery(inner, "", "outer.Op", "outer failed", true, &retryAfter, "retry later")
var logErr *Err
assert.True(t, As(outer, &logErr))
assert.Equal(t, "", logErr.Code)
}
func TestWrapCode_Good_NilError(t *testing.T) {
// WrapCode with nil error but with code still creates an error
err := WrapCode(nil, "CODE", "op", "msg")
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "[CODE]")
}
func TestErrors_WrapCode_Ugly(t *testing.T) {
// nil error AND empty code — only then returns nil
err := WrapCode(nil, "", "op", "msg")
// Only returns nil when both error and code are empty
err = WrapCode(nil, "", "op", "msg")
assert.Nil(t, err)
}
// --- NewCode ---
func TestErrors_NewCode_Good(t *testing.T) {
func TestNewCode_Good(t *testing.T) {
err := NewCode("NOT_FOUND", "resource not found")
var typedError *Err
assert.True(t, errors.As(err, &typedError))
assert.Equal(t, "NOT_FOUND", typedError.Code)
assert.Equal(t, "resource not found", typedError.Msg)
assert.Nil(t, typedError.Err)
var logErr *Err
assert.True(t, errors.As(err, &logErr))
assert.Equal(t, "NOT_FOUND", logErr.Code)
assert.Equal(t, "resource not found", logErr.Msg)
assert.Nil(t, logErr.Err)
}
func TestErrors_NewCode_Bad(t *testing.T) {
// Empty code is preserved as-is
err := NewCode("", "no code error")
func TestNewCodeWithRecovery_Good(t *testing.T) {
retryAfter := 2 * time.Minute
err := NewCodeWithRecovery("NOT_FOUND", "resource not found", false, &retryAfter, "contact support")
var logErr *Err
assert.NotNil(t, err)
assert.Equal(t, "no code error", err.Error())
assert.True(t, As(err, &logErr))
assert.False(t, logErr.Retryable)
assert.NotNil(t, logErr.RetryAfter)
assert.Equal(t, retryAfter, *logErr.RetryAfter)
assert.Equal(t, "contact support", logErr.NextAction)
}
func TestErrors_NewCode_Ugly(t *testing.T) {
// NewCode result can be used as a sentinel value
sentinel := NewCode("SENTINEL", "sentinel error")
wrapped := Wrap(sentinel, "caller.Op", "something went wrong")
assert.True(t, Is(wrapped, sentinel))
}
// --- Standard Library Wrapper Tests ---
// --- Is ---
func TestErrors_Is_Good(t *testing.T) {
func TestIs_Good(t *testing.T) {
sentinel := errors.New("sentinel")
wrapped := Wrap(sentinel, "test", "wrapped")
assert.True(t, Is(wrapped, sentinel))
assert.False(t, Is(wrapped, errors.New("other")))
}
func TestErrors_Is_Bad(t *testing.T) {
// Different errors are not equal
assert.False(t, Is(errors.New("a"), errors.New("b")))
}
func TestErrors_Is_Ugly(t *testing.T) {
// nil target
assert.False(t, Is(errors.New("something"), nil))
// nil err
assert.False(t, Is(nil, errors.New("something")))
// both nil
assert.True(t, Is(nil, nil))
}
// --- As ---
func TestErrors_As_Good(t *testing.T) {
func TestAs_Good(t *testing.T) {
err := E("test.Op", "message", errors.New("base"))
var typedError *Err
assert.True(t, As(err, &typedError))
assert.Equal(t, "test.Op", typedError.Op)
var logErr *Err
assert.True(t, As(err, &logErr))
assert.Equal(t, "test.Op", logErr.Op)
}
func TestErrors_As_Bad(t *testing.T) {
// As returns false for non-matching types
err := errors.New("plain")
var typedError *Err
assert.False(t, As(err, &typedError))
}
func TestErrors_As_Ugly(t *testing.T) {
// As traverses the chain to find *Err
plain := errors.New("base")
wrapped := Wrap(plain, "op", "msg")
doubleWrapped := fmt.Errorf("fmt wrapper: %w", wrapped)
var typedError *Err
assert.True(t, As(doubleWrapped, &typedError))
assert.Equal(t, "op", typedError.Op)
}
// --- NewError ---
func TestErrors_NewError_Good(t *testing.T) {
func TestNewError_Good(t *testing.T) {
err := NewError("simple error")
assert.NotNil(t, err)
assert.Equal(t, "simple error", err.Error())
}
func TestErrors_NewError_Bad(t *testing.T) {
// Two NewError calls with same text are distinct values
a := NewError("same text")
b := NewError("same text")
assert.False(t, Is(a, b), "two NewError values with same text must not match via Is")
}
func TestErrors_NewError_Ugly(t *testing.T) {
// Empty text produces an error with empty message
err := NewError("")
assert.NotNil(t, err)
assert.Equal(t, "", err.Error())
}
// --- Join ---
func TestErrors_Join_Good(t *testing.T) {
func TestJoin_Good(t *testing.T) {
err1 := errors.New("error 1")
err2 := errors.New("error 2")
joined := Join(err1, err2)
@ -262,78 +278,88 @@ func TestErrors_Join_Good(t *testing.T) {
assert.True(t, errors.Is(joined, err2))
}
func TestErrors_Join_Bad(t *testing.T) {
// All nil — returns nil
assert.Nil(t, Join(nil, nil))
}
// --- Helper Function Tests ---
func TestErrors_Join_Ugly(t *testing.T) {
// Mix of nil and non-nil — non-nil are preserved
err := errors.New("only error")
joined := Join(nil, err, nil)
assert.True(t, errors.Is(joined, err))
}
// --- Op ---
func TestErrors_Op_Good(t *testing.T) {
func TestOp_Good(t *testing.T) {
err := E("mypackage.MyFunc", "failed", errors.New("cause"))
assert.Equal(t, "mypackage.MyFunc", Op(err))
}
func TestErrors_Op_Bad(t *testing.T) {
// Plain error has no op
func TestOp_Good_NotLogError(t *testing.T) {
err := errors.New("plain error")
assert.Equal(t, "", Op(err))
}
func TestErrors_Op_Ugly(t *testing.T) {
// Outer op is returned, not inner
inner := E("inner.Op", "inner", nil)
outer := Wrap(inner, "outer.Op", "outer")
assert.Equal(t, "outer.Op", Op(outer))
}
// --- ErrCode ---
func TestErrors_ErrCode_Good(t *testing.T) {
func TestErrCode_Good(t *testing.T) {
err := WrapCode(errors.New("base"), "ERR_CODE", "op", "msg")
assert.Equal(t, "ERR_CODE", ErrCode(err))
}
func TestErrors_ErrCode_Bad(t *testing.T) {
// No code on a plain *Err
func TestErrCode_Good_NoCode(t *testing.T) {
err := E("op", "msg", errors.New("base"))
assert.Equal(t, "", ErrCode(err))
}
func TestErrors_ErrCode_Ugly(t *testing.T) {
// Nil and plain errors both return empty string
assert.Equal(t, "", ErrCode(nil))
assert.Equal(t, "", ErrCode(errors.New("plain")))
func TestErrCode_Good_PlainError(t *testing.T) {
err := errors.New("plain error")
assert.Equal(t, "", ErrCode(err))
}
// --- Message ---
func TestErrCode_Good_Nil(t *testing.T) {
assert.Equal(t, "", ErrCode(nil))
}
func TestErrors_Message_Good(t *testing.T) {
func TestRetryAfter_Good(t *testing.T) {
retryAfter := 42 * time.Second
err := &Err{Msg: "typed", RetryAfter: &retryAfter}
got, ok := RetryAfter(err)
assert.True(t, ok)
assert.Equal(t, retryAfter, *got)
}
func TestRetryAfter_Good_NestedChain(t *testing.T) {
retryAfter := 42 * time.Second
inner := &Err{Msg: "typed", RetryAfter: &retryAfter}
outer := &Err{Msg: "outer", Err: inner}
got, ok := RetryAfter(outer)
assert.True(t, ok)
assert.Equal(t, retryAfter, *got)
}
func TestIsRetryable_Good(t *testing.T) {
err := &Err{Msg: "typed", Retryable: true}
assert.True(t, IsRetryable(err))
}
func TestRecoveryAction_Good(t *testing.T) {
err := &Err{Msg: "typed", NextAction: "inspect"}
assert.Equal(t, "inspect", RecoveryAction(err))
}
func TestRecoveryAction_Good_NestedChain(t *testing.T) {
inner := &Err{Msg: "typed", NextAction: "inspect"}
outer := &Err{Msg: "outer", Err: inner}
assert.Equal(t, "inspect", RecoveryAction(outer))
}
func TestMessage_Good(t *testing.T) {
err := E("op", "the message", errors.New("base"))
assert.Equal(t, "the message", Message(err))
}
func TestErrors_Message_Bad(t *testing.T) {
// Plain error — falls back to Error() string
func TestMessage_Good_PlainError(t *testing.T) {
err := errors.New("plain message")
assert.Equal(t, "plain message", Message(err))
}
func TestErrors_Message_Ugly(t *testing.T) {
// Nil returns empty string
func TestMessage_Good_Nil(t *testing.T) {
assert.Equal(t, "", Message(nil))
}
// --- Root ---
func TestErrors_Root_Good(t *testing.T) {
func TestRoot_Good(t *testing.T) {
root := errors.New("root cause")
level1 := Wrap(root, "level1", "wrapped once")
level2 := Wrap(level1, "level2", "wrapped twice")
@ -341,88 +367,19 @@ func TestErrors_Root_Good(t *testing.T) {
assert.Equal(t, root, Root(level2))
}
func TestErrors_Root_Bad(t *testing.T) {
// Single unwrapped error returns itself
func TestRoot_Good_SingleError(t *testing.T) {
err := errors.New("single")
assert.Equal(t, err, Root(err))
}
func TestErrors_Root_Ugly(t *testing.T) {
// Nil returns nil
func TestRoot_Good_Nil(t *testing.T) {
assert.Nil(t, Root(nil))
}
// --- StackTrace / FormatStackTrace ---
// --- Log-and-Return Helper Tests ---
func TestErrors_StackTrace_Good(t *testing.T) {
err := E("op1", "msg1", nil)
err = Wrap(err, "op2", "msg2")
err = Wrap(err, "op3", "msg3")
stack := StackTrace(err)
assert.Equal(t, []string{"op3", "op2", "op1"}, stack)
formatted := FormatStackTrace(err)
assert.Equal(t, "op3 -> op2 -> op1", formatted)
}
func TestErrors_StackTrace_Bad(t *testing.T) {
// Plain error has no ops in the stack
err := errors.New("plain error")
assert.Empty(t, StackTrace(err))
assert.Empty(t, FormatStackTrace(err))
}
func TestErrors_StackTrace_Ugly(t *testing.T) {
// Nil and *Err with no Op both yield empty stack
assert.Empty(t, StackTrace(nil))
assert.Empty(t, FormatStackTrace(nil))
assert.Empty(t, StackTrace(&Err{Msg: "no op"}))
// Mixed chain: fmt.Errorf wrapper in the middle — ops on both sides still appear
inner := E("inner", "msg", nil)
wrapped := fmt.Errorf("fmt wrapper: %w", inner)
outer := Wrap(wrapped, "outer", "msg")
stack := StackTrace(outer)
assert.Equal(t, []string{"outer", "inner"}, stack)
}
// --- AllOps ---
func TestErrors_AllOps_Good(t *testing.T) {
err := E("op1", "msg1", nil)
err = Wrap(err, "op2", "msg2")
var ops []string
for op := range AllOps(err) {
ops = append(ops, op)
}
assert.Equal(t, []string{"op2", "op1"}, ops)
}
func TestErrors_AllOps_Bad(t *testing.T) {
// Plain error yields no ops
err := errors.New("plain")
var ops []string
for op := range AllOps(err) {
ops = append(ops, op)
}
assert.Empty(t, ops)
}
func TestErrors_AllOps_Ugly(t *testing.T) {
// Nil error — iterator yields nothing, no panic
var ops []string
for op := range AllOps(nil) {
ops = append(ops, op)
}
assert.Empty(t, ops)
}
// --- LogError ---
func TestErrors_LogError_Good(t *testing.T) {
func TestLogError_Good(t *testing.T) {
// Capture log output
var buf bytes.Buffer
logger := New(Options{Level: LevelDebug, Output: &buf})
SetDefault(logger)
@ -431,19 +388,37 @@ func TestErrors_LogError_Good(t *testing.T) {
underlying := errors.New("connection failed")
err := LogError(underlying, "db.Connect", "database unavailable")
// Check returned error
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "db.Connect")
assert.Contains(t, err.Error(), "database unavailable")
assert.True(t, errors.Is(err, underlying))
// Check log output
output := buf.String()
assert.Contains(t, output, "[ERR]")
assert.Contains(t, output, "database unavailable")
assert.Contains(t, output, "op=\"db.Connect\"")
}
func TestErrors_LogError_Bad(t *testing.T) {
// nil error — returns nil, no log output
func TestLogError_Good_LogsOriginalErrorContext(t *testing.T) {
var buf bytes.Buffer
logger := New(Options{Level: LevelDebug, Output: &buf})
SetDefault(logger)
defer SetDefault(New(Options{Level: LevelInfo}))
underlying := E("db.Query", "query failed", errors.New("timeout"))
err := LogError(underlying, "db.Connect", "database unavailable")
assert.NotNil(t, err)
output := buf.String()
assert.Contains(t, output, "op=\"db.Connect\"")
assert.Contains(t, output, "stack=\"db.Query\"")
assert.NotContains(t, output, "stack=\"db.Connect -> db.Query\"")
}
func TestLogError_Good_NilError(t *testing.T) {
var buf bytes.Buffer
logger := New(Options{Level: LevelDebug, Output: &buf})
SetDefault(logger)
@ -451,27 +426,10 @@ func TestErrors_LogError_Bad(t *testing.T) {
err := LogError(nil, "op", "msg")
assert.Nil(t, err)
assert.Empty(t, buf.String())
assert.Empty(t, buf.String()) // No log output for nil error
}
func TestErrors_LogError_Ugly(t *testing.T) {
// LogError on an already-wrapped *Err — error chain preserved
var buf bytes.Buffer
logger := New(Options{Level: LevelDebug, Output: &buf})
SetDefault(logger)
defer SetDefault(New(Options{Level: LevelInfo}))
root := errors.New("root")
inner := E("inner.Op", "inner failed", root)
err := LogError(inner, "outer.Op", "outer context")
assert.True(t, errors.Is(err, root))
assert.Contains(t, buf.String(), "[ERR]")
}
// --- LogWarn ---
func TestErrors_LogWarn_Good(t *testing.T) {
func TestLogWarn_Good(t *testing.T) {
var buf bytes.Buffer
logger := New(Options{Level: LevelDebug, Output: &buf})
SetDefault(logger)
@ -482,12 +440,13 @@ func TestErrors_LogWarn_Good(t *testing.T) {
assert.NotNil(t, err)
assert.True(t, errors.Is(err, underlying))
assert.Contains(t, buf.String(), "[WRN]")
assert.Contains(t, buf.String(), "falling back to db")
output := buf.String()
assert.Contains(t, output, "[WRN]")
assert.Contains(t, output, "falling back to db")
}
func TestErrors_LogWarn_Bad(t *testing.T) {
// nil error — returns nil, no log output
func TestLogWarn_Good_NilError(t *testing.T) {
var buf bytes.Buffer
logger := New(Options{Level: LevelDebug, Output: &buf})
SetDefault(logger)
@ -498,28 +457,14 @@ func TestErrors_LogWarn_Bad(t *testing.T) {
assert.Empty(t, buf.String())
}
func TestErrors_LogWarn_Ugly(t *testing.T) {
// LogWarn at LevelError — [WRN] is suppressed since Warn < Error threshold
var buf bytes.Buffer
logger := New(Options{Level: LevelError, Output: &buf})
SetDefault(logger)
defer SetDefault(New(Options{Level: LevelInfo}))
LogWarn(errors.New("warn level"), "op", "msg")
assert.Empty(t, buf.String(), "expected warn suppressed at LevelError")
}
// --- Must ---
func TestErrors_Must_Good(t *testing.T) {
// nil error — no panic
func TestMust_Good_NoError(t *testing.T) {
// Should not panic when error is nil
assert.NotPanics(t, func() {
Must(nil, "test", "should not panic")
})
}
func TestErrors_Must_Bad(t *testing.T) {
// Non-nil error — panics with wrapped error
func TestMust_Ugly_Panics(t *testing.T) {
var buf bytes.Buffer
logger := New(Options{Level: LevelDebug, Output: &buf})
SetDefault(logger)
@ -529,21 +474,47 @@ func TestErrors_Must_Bad(t *testing.T) {
Must(errors.New("fatal error"), "startup", "initialization failed")
})
// Verify error was logged before panic
output := buf.String()
assert.True(t, core.Contains(output, "[ERR]") || len(output) > 0)
assert.True(t, strings.Contains(output, "[ERR]") || len(output) > 0)
}
func TestErrors_Must_Ugly(t *testing.T) {
// Panic value is a wrapped *Err, not the raw error
var panicValue any
func() {
defer func() { panicValue = recover() }()
Must(errors.New("root cause"), "init.Op", "startup failed")
}()
func TestStackTrace_Good(t *testing.T) {
// Nested operations
err := E("op1", "msg1", nil)
err = Wrap(err, "op2", "msg2")
err = Wrap(err, "op3", "msg3")
assert.NotNil(t, panicValue)
panicErr, ok := panicValue.(error)
assert.True(t, ok, "panic value must be an error")
assert.Contains(t, panicErr.Error(), "init.Op")
assert.Contains(t, panicErr.Error(), "startup failed")
stack := StackTrace(err)
assert.Equal(t, []string{"op3", "op2", "op1"}, stack)
// Format
formatted := FormatStackTrace(err)
assert.Equal(t, "op3 -> op2 -> op1", formatted)
}
func TestStackTrace_Bad_PlainError(t *testing.T) {
err := errors.New("plain error")
assert.Empty(t, StackTrace(err))
assert.Empty(t, FormatStackTrace(err))
}
func TestStackTrace_Bad_Nil(t *testing.T) {
assert.Empty(t, StackTrace(nil))
assert.Empty(t, FormatStackTrace(nil))
}
func TestStackTrace_Bad_NoOp(t *testing.T) {
err := &Err{Msg: "no op"}
assert.Empty(t, StackTrace(err))
assert.Empty(t, FormatStackTrace(err))
}
func TestStackTrace_Mixed_Good(t *testing.T) {
err := E("inner", "msg", nil)
err = fmt.Errorf("wrapper: %w", err)
err = Wrap(err, "outer", "msg")
stack := StackTrace(err)
assert.Equal(t, []string{"outer", "inner"}, stack)
}

9
go.mod
View file

@ -2,14 +2,13 @@ module dappco.re/go/core/log
go 1.26.0
require (
dappco.re/go/core v0.6.0
github.com/stretchr/testify v1.11.1
)
require github.com/stretchr/testify v1.11.1
require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/kr/text v0.2.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/rogpeppe/go-internal v1.14.1 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

7
go.sum
View file

@ -1,14 +1,17 @@
dappco.re/go/core v0.6.0 h1:0wmuO/UmCWXxJkxQ6XvVLnqkAuWitbd49PhxjCsplyk=
dappco.re/go/core v0.6.0/go.mod h1:f2/tBZ3+3IqDrg2F5F598llv0nmb/4gJVCFzM5geE4A=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=

264
log.go
View file

@ -6,12 +6,12 @@
package log
import (
"dappco.re/go/core"
"fmt"
goio "io"
"os"
"os/user"
"slices"
"strings"
"sync"
"time"
)
@ -33,6 +33,19 @@ const (
LevelDebug
)
const (
defaultRotationMaxSize = 100
defaultRotationMaxAge = 28
defaultRotationMaxBackups = 5
)
func normaliseLevel(level Level) Level {
if level < LevelQuiet || level > LevelDebug {
return LevelInfo
}
return level
}
// String returns the level name.
func (l Level) String() string {
switch l {
@ -60,13 +73,18 @@ type Logger struct {
// RedactKeys is a list of keys whose values should be masked in logs.
redactKeys []string
// Style functions for formatting (can be overridden)
// StyleTimestamp formats the rendered timestamp prefix.
StyleTimestamp func(string) string
StyleDebug func(string) string
StyleInfo func(string) string
StyleWarn func(string) string
StyleError func(string) string
StyleSecurity func(string) string
// StyleDebug formats the debug level prefix.
StyleDebug func(string) string
// StyleInfo formats the info level prefix.
StyleInfo func(string) string
// StyleWarn formats the warning level prefix.
StyleWarn func(string) string
// StyleError formats the error level prefix.
StyleError func(string) string
// StyleSecurity formats the security event prefix.
StyleSecurity func(string) string
}
// RotationOptions defines the log rotation and retention policy.
@ -94,6 +112,7 @@ type RotationOptions struct {
// Options configures a Logger.
type Options struct {
// Level controls which messages are emitted.
Level Level
// Output is the destination for log messages. If Rotation is provided,
// Output is ignored and logs are written to the rotating file instead.
@ -110,19 +129,24 @@ var RotationWriterFactory func(RotationOptions) goio.WriteCloser
// New creates a new Logger with the given options.
//
// logger := log.New(log.Options{Level: log.LevelInfo, Output: os.Stderr})
// logger := log.New(log.Options{Level: log.LevelDebug, RedactKeys: []string{"password"}})
// logger := log.New(log.Options{
// Level: log.LevelInfo,
// Output: os.Stdout,
// RedactKeys: []string{"password", "token"},
// })
func New(opts Options) *Logger {
level := normaliseLevel(opts.Level)
output := opts.Output
if opts.Rotation != nil && opts.Rotation.Filename != "" && RotationWriterFactory != nil {
output = RotationWriterFactory(*opts.Rotation)
output = RotationWriterFactory(normaliseRotationOptions(*opts.Rotation))
}
if output == nil {
output = os.Stderr
}
return &Logger{
level: opts.Level,
level: level,
output: output,
redactKeys: slices.Clone(opts.RedactKeys),
StyleTimestamp: identity,
@ -134,14 +158,34 @@ func New(opts Options) *Logger {
}
}
func normaliseRotationOptions(opts RotationOptions) RotationOptions {
if opts.MaxSize <= 0 {
opts.MaxSize = defaultRotationMaxSize
}
if opts.MaxAge == 0 {
opts.MaxAge = defaultRotationMaxAge
}
if opts.MaxBackups <= 0 {
opts.MaxBackups = defaultRotationMaxBackups
}
return opts
}
func identity(s string) string { return s }
func safeStyle(style func(string) string) func(string) string {
if style == nil {
return identity
}
return style
}
// SetLevel changes the log level.
//
// logger.SetLevel(log.LevelDebug)
func (l *Logger) SetLevel(level Level) {
l.mu.Lock()
l.level = level
l.level = normaliseLevel(level)
l.mu.Unlock()
}
@ -158,6 +202,9 @@ func (l *Logger) Level() Level {
//
// logger.SetOutput(os.Stdout)
func (l *Logger) SetOutput(w goio.Writer) {
if w == nil {
w = os.Stderr
}
l.mu.Lock()
l.output = w
l.mu.Unlock()
@ -179,79 +226,98 @@ func (l *Logger) shouldLog(level Level) bool {
}
func (l *Logger) log(level Level, prefix, msg string, keyvals ...any) {
_ = level
l.mu.RLock()
output := l.output
styleTimestamp := l.StyleTimestamp
redactKeys := l.redactKeys
l.mu.RUnlock()
if styleTimestamp == nil {
styleTimestamp = identity
}
timestamp := styleTimestamp(time.Now().Format("15:04:05"))
existing := make(map[string]struct{}, len(keyvals)/2+2)
for i := 0; i < len(keyvals); i += 2 {
if key, ok := keyvals[i].(string); ok {
existing[key] = struct{}{}
}
}
// Automatically extract context from error if present in keyvals
originalLength := len(keyvals)
for i := 0; i < originalLength; i += 2 {
if i+1 < originalLength {
if err, ok := keyvals[i+1].(error); ok {
if op := Op(err); op != "" {
// Check if op is already in keyvals
hasOperationKey := false
for j := 0; j < len(keyvals); j += 2 {
if k, ok := keyvals[j].(string); ok && k == "op" {
hasOperationKey = true
break
}
}
if !hasOperationKey {
keyvals = append(keyvals, "op", op)
}
origLen := len(keyvals)
for i := 0; i < origLen; i += 2 {
if i+1 >= origLen {
continue
}
err, ok := keyvals[i+1].(error)
if !ok {
continue
}
var logErr *Err
if As(err, &logErr) {
if _, hasRetryable := existing["retryable"]; !hasRetryable {
existing["retryable"] = struct{}{}
keyvals = append(keyvals, "retryable", retryableHint(err))
}
if retryAfter, ok := RetryAfter(err); ok {
if _, hasRetryAfter := existing["retry_after_seconds"]; !hasRetryAfter {
existing["retry_after_seconds"] = struct{}{}
keyvals = append(keyvals, "retry_after_seconds", retryAfter.Seconds())
}
if stack := FormatStackTrace(err); stack != "" {
// Check if stack is already in keyvals
hasStackKey := false
for j := 0; j < len(keyvals); j += 2 {
if k, ok := keyvals[j].(string); ok && k == "stack" {
hasStackKey = true
break
}
}
if !hasStackKey {
keyvals = append(keyvals, "stack", stack)
}
}
if nextAction := RecoveryAction(err); nextAction != "" {
if _, hasNextAction := existing["next_action"]; !hasNextAction {
existing["next_action"] = struct{}{}
keyvals = append(keyvals, "next_action", nextAction)
}
}
}
if op := Op(err); op != "" {
if _, hasOp := existing["op"]; !hasOp {
existing["op"] = struct{}{}
keyvals = append(keyvals, "op", op)
}
}
if stack := FormatStackTrace(err); stack != "" {
if _, hasStack := existing["stack"]; !hasStack {
existing["stack"] = struct{}{}
keyvals = append(keyvals, "stack", stack)
}
}
}
// Format key-value pairs
var keyValueString string
var kvStr string
if len(keyvals) > 0 {
keyValueString = " "
kvStr = " "
for i := 0; i < len(keyvals); i += 2 {
if i > 0 {
keyValueString += " "
kvStr += " "
}
key := keyvals[i]
key := normaliseLogText(fmt.Sprintf("%v", keyvals[i]))
var val any
if i+1 < len(keyvals) {
val = keyvals[i+1]
}
// Redaction logic
keyStr := core.Sprintf("%v", key)
if slices.Contains(redactKeys, keyStr) {
if shouldRedact(key, redactKeys) {
val = "[REDACTED]"
}
// Secure formatting to prevent log injection
if s, ok := val.(string); ok {
keyValueString += core.Sprintf("%v=%q", key, s)
kvStr += fmt.Sprintf("%s=%q", key, s)
} else {
keyValueString += core.Sprintf("%v=%v", key, val)
kvStr += fmt.Sprintf("%s=%v", key, normaliseLogText(fmt.Sprintf("%v", val)))
}
}
}
_, _ = fmt.Fprintf(output, "%s %s %s%s\n", timestamp, prefix, msg, keyValueString)
_, _ = fmt.Fprintf(output, "%s %s %s%s\n", timestamp, prefix, normaliseLogText(msg), kvStr)
}
// Debug logs a debug message with optional key-value pairs.
@ -259,7 +325,10 @@ func (l *Logger) log(level Level, prefix, msg string, keyvals ...any) {
// logger.Debug("processing request", "method", "GET", "path", "/api/users")
func (l *Logger) Debug(msg string, keyvals ...any) {
if l.shouldLog(LevelDebug) {
l.log(LevelDebug, l.StyleDebug("[DBG]"), msg, keyvals...)
l.mu.RLock()
style := safeStyle(l.StyleDebug)
l.mu.RUnlock()
l.log(LevelDebug, style("[DBG]"), msg, keyvals...)
}
}
@ -268,7 +337,10 @@ func (l *Logger) Debug(msg string, keyvals ...any) {
// logger.Info("server started", "port", 8080)
func (l *Logger) Info(msg string, keyvals ...any) {
if l.shouldLog(LevelInfo) {
l.log(LevelInfo, l.StyleInfo("[INF]"), msg, keyvals...)
l.mu.RLock()
style := safeStyle(l.StyleInfo)
l.mu.RUnlock()
l.log(LevelInfo, style("[INF]"), msg, keyvals...)
}
}
@ -277,7 +349,10 @@ func (l *Logger) Info(msg string, keyvals ...any) {
// logger.Warn("high memory usage", "percent", 92)
func (l *Logger) Warn(msg string, keyvals ...any) {
if l.shouldLog(LevelWarn) {
l.log(LevelWarn, l.StyleWarn("[WRN]"), msg, keyvals...)
l.mu.RLock()
style := safeStyle(l.StyleWarn)
l.mu.RUnlock()
l.log(LevelWarn, style("[WRN]"), msg, keyvals...)
}
}
@ -286,7 +361,10 @@ func (l *Logger) Warn(msg string, keyvals ...any) {
// logger.Error("database connection failed", "err", err, "host", "db.local")
func (l *Logger) Error(msg string, keyvals ...any) {
if l.shouldLog(LevelError) {
l.log(LevelError, l.StyleError("[ERR]"), msg, keyvals...)
l.mu.RLock()
style := safeStyle(l.StyleError)
l.mu.RUnlock()
l.log(LevelError, style("[ERR]"), msg, keyvals...)
}
}
@ -297,87 +375,123 @@ func (l *Logger) Error(msg string, keyvals ...any) {
// logger.Security("brute force detected", "ip", remoteAddr, "attempts", 50)
func (l *Logger) Security(msg string, keyvals ...any) {
if l.shouldLog(LevelError) {
l.log(LevelError, l.StyleSecurity("[SEC]"), msg, keyvals...)
l.mu.RLock()
style := safeStyle(l.StyleSecurity)
l.mu.RUnlock()
l.log(LevelError, style("[SEC]"), msg, keyvals...)
}
}
// Username returns the current system username.
// It uses os/user for reliability and falls back to environment variables.
//
// owner := log.Username() // e.g. "deploy", "www-data"
// user := log.Username()
func Username() string {
if u, err := user.Current(); err == nil {
return u.Username
}
// Fallback for environments where user lookup might fail
if u := core.Env("USER"); u != "" {
if u := os.Getenv("USER"); u != "" {
return u
}
return core.Env("USERNAME")
if u := os.Getenv("USERNAME"); u != "" {
return u
}
return "unknown"
}
var logTextCleaner = strings.NewReplacer(
"\r", "\\r",
"\n", "\\n",
"\t", "\\t",
)
func normaliseLogText(text string) string {
return logTextCleaner.Replace(text)
}
// --- Default logger ---
var defaultLogger = New(Options{Level: LevelInfo})
var defaultLoggerMu sync.RWMutex
// Default returns the default logger.
//
// logger := log.Default()
func Default() *Logger {
defaultLoggerMu.RLock()
defer defaultLoggerMu.RUnlock()
return defaultLogger
}
// SetDefault sets the default logger.
// Passing nil is ignored to preserve the current default logger.
//
// log.SetDefault(customLogger)
func SetDefault(l *Logger) {
if l == nil {
return
}
defaultLoggerMu.Lock()
defaultLogger = l
defaultLoggerMu.Unlock()
}
// SetLevel sets the default logger's level.
//
// log.SetLevel(log.LevelDebug)
func SetLevel(level Level) {
defaultLogger.SetLevel(level)
Default().SetLevel(level)
}
// SetRedactKeys sets the default logger's redaction keys.
//
// log.SetRedactKeys("password", "token", "api_key")
// log.SetRedactKeys("password", "token")
func SetRedactKeys(keys ...string) {
defaultLogger.SetRedactKeys(keys...)
Default().SetRedactKeys(keys...)
}
// Debug logs a debug message to the default logger.
// Debug logs to the default logger.
//
// log.Debug("cache lookup", "key", "user:42", "hit", false)
// log.Debug("query started", "sql", query)
func Debug(msg string, keyvals ...any) {
defaultLogger.Debug(msg, keyvals...)
Default().Debug(msg, keyvals...)
}
// Info logs an informational message to the default logger.
// Info logs to the default logger.
//
// log.Info("server started", "port", 8080)
// log.Info("server ready", "port", 8080)
func Info(msg string, keyvals ...any) {
defaultLogger.Info(msg, keyvals...)
Default().Info(msg, keyvals...)
}
// Warn logs a warning message to the default logger.
// Warn logs to the default logger.
//
// log.Warn("retrying", "attempt", 2, "max", 3)
// log.Warn("retrying request", "attempt", 2)
func Warn(msg string, keyvals ...any) {
defaultLogger.Warn(msg, keyvals...)
Default().Warn(msg, keyvals...)
}
// Error logs an error message to the default logger.
// Error logs to the default logger.
//
// log.Error("request failed", "err", err, "path", r.URL.Path)
// log.Error("request failed", "err", err)
func Error(msg string, keyvals ...any) {
defaultLogger.Error(msg, keyvals...)
Default().Error(msg, keyvals...)
}
// Security logs a security event to the default logger.
// Security logs to the default logger.
//
// log.Security("login failed", "ip", remoteAddr, "user", username)
// log.Security("suspicious login", "ip", remoteAddr)
func Security(msg string, keyvals ...any) {
defaultLogger.Security(msg, keyvals...)
Default().Security(msg, keyvals...)
}
func shouldRedact(key any, redactKeys []string) bool {
keyStr := fmt.Sprintf("%v", key)
for _, redactKey := range redactKeys {
if redactKey == keyStr {
return true
}
}
return false
}

File diff suppressed because it is too large Load diff

266
specs/RFC.md Normal file
View file

@ -0,0 +1,266 @@
# log
**Import:** `dappco.re/go/core/log`
**Files:** 2
## Types
### Err
`type Err struct`
Structured error wrapper that carries operation context, a human-readable message, an optional wrapped cause, and an optional machine-readable code.
It can also carry agent-facing recovery metadata that survives wrapping and is
surfaced automatically in structured logs.
Fields:
- `Op string`: operation name. When non-empty, `Error` prefixes the formatted message with `Op + ": "`.
- `Msg string`: human-readable message stored on the error and returned by `Message`.
- `Err error`: wrapped cause returned by `Unwrap`.
- `Code string`: optional machine-readable code. When non-empty, `Error` includes it in square brackets.
- `Retryable bool`: whether the caller can safely retry the operation.
- `RetryAfter *time.Duration`: optional retry delay hint when `Retryable` is true.
- `NextAction string`: suggested next step when the error is not directly retryable.
Methods:
- `func (e *Err) Error() string`: formats the error text from `Op`, `Msg`, `Code`, and `Err`. The result omits missing parts, so the output can be `"{Msg}"`, `"{Msg} [{Code}]"`, `"{Msg}: {Err}"`, `"{Op}: {Msg} [{Code}]: {Err}"`, or a cleanly collapsed form such as `"{Op}"` when no message, code, or cause is present.
- `func (e *Err) Unwrap() error`: returns `e.Err`.
### Level
`type Level int`
Logging verbosity enum used by `Logger` and `Options`.
Methods:
- `func (l Level) String() string`: returns `quiet`, `error`, `warn`, `info`, or `debug`. Any other value returns `unknown`.
### Logger
`type Logger struct`
Concurrency-safe structured logger. `New` clones the configured redaction keys, stores the configured level and writer, and initializes all style hooks to identity functions.
Each log call writes one line in the form `HH:MM:SS {prefix} {msg}` followed by space-separated key/value pairs. String values are rendered with Go `%q` quoting, redacted keys are replaced with `"[REDACTED]"`, a trailing key without a value renders as `<nil>`, and any `error` value in `keyvals` can cause `op`, `stack`, `retryable`, `retry_after_seconds`, and `next_action` fields to be appended automatically if those keys were not already supplied.
Fields:
- `StyleTimestamp func(string) string`: transforms the rendered `HH:MM:SS` timestamp before it is written.
- `StyleDebug func(string) string`: transforms the debug prefix passed to debug log lines.
- `StyleInfo func(string) string`: transforms the info prefix passed to info log lines.
- `StyleWarn func(string) string`: transforms the warn prefix passed to warning log lines.
- `StyleError func(string) string`: transforms the error prefix passed to error log lines.
- `StyleSecurity func(string) string`: transforms the security prefix passed to security log lines.
Methods:
- `func (l *Logger) SetLevel(level Level)`: sets the loggers current threshold.
- `func (l *Logger) Level() Level`: returns the loggers current threshold.
- `func (l *Logger) SetOutput(w goio.Writer)`: replaces the writer used for future log lines.
- `func (l *Logger) SetRedactKeys(keys ...string)`: replaces the exact-match key list whose values are masked during formatting.
- `func (l *Logger) Debug(msg string, keyvals ...any)`: emits a debug line when the logger level is at least `LevelDebug`.
- `func (l *Logger) Info(msg string, keyvals ...any)`: emits an info line when the logger level is at least `LevelInfo`.
- `func (l *Logger) Warn(msg string, keyvals ...any)`: emits a warning line when the logger level is at least `LevelWarn`.
- `func (l *Logger) Error(msg string, keyvals ...any)`: emits an error line when the logger level is at least `LevelError`.
- `func (l *Logger) Security(msg string, keyvals ...any)`: emits a security line with the security style prefix and the same visibility threshold as `LevelError`.
### Options
`type Options struct`
Constructor input for `New`.
Fields:
- `Level Level`: initial logger threshold.
- `Output goio.Writer`: destination used when rotation is not selected.
- `Rotation *RotationOptions`: optional rotation configuration. `New` uses rotation only when this field is non-nil, `Rotation.Filename` is non-empty, and `RotationWriterFactory` is non-nil.
- `RedactKeys []string`: keys whose values should be masked in formatted log output.
### RotationOptions
`type RotationOptions struct`
Rotation configuration passed through to `RotationWriterFactory` when `New` selects a rotating writer.
Fields:
- `Filename string`: log file path. `New` only attempts rotation when this field is non-empty.
- `MaxSize int`: value forwarded to the rotation writer factory.
- `MaxAge int`: value forwarded to the rotation writer factory.
- `MaxBackups int`: value forwarded to the rotation writer factory.
- `Compress bool`: value forwarded to the rotation writer factory.
## Functions
### AllOps
`func AllOps(err error) iter.Seq[string]`
Returns an iterator over non-empty `Op` values found by repeatedly calling `errors.Unwrap` on `err`. Operations are yielded from the outermost `*Err` to the innermost one.
### As
`func As(err error, target any) bool`
Thin wrapper around `errors.As`.
### Debug
`func Debug(msg string, keyvals ...any)`
Calls `Default().Debug(msg, keyvals...)`.
### Default
`func Default() *Logger`
Returns the package-level default logger. The package initializes it with `New(Options{Level: LevelInfo})`.
### E
`func E(op, msg string, err error) error`
Returns `&Err{Op: op, Msg: msg, Err: err}` as an `error`. It always returns a non-nil error value, even when `err` is nil.
### EWithRecovery
`func EWithRecovery(op, msg string, err error, retryable bool, retryAfter *time.Duration, nextAction string) error`
Returns `&Err{Op: op, Msg: msg, Err: err}` with explicit recovery metadata
attached to the new error value.
### ErrCode
`func ErrCode(err error) string`
If `err` contains an `*Err`, returns its `Code`. Otherwise returns the empty string.
### Error
`func Error(msg string, keyvals ...any)`
Calls `Default().Error(msg, keyvals...)`.
### FormatStackTrace
`func FormatStackTrace(err error) string`
Collects `AllOps(err)` and joins the operations with `" -> "`. Returns the empty string when no operations are found.
### Info
`func Info(msg string, keyvals ...any)`
Calls `Default().Info(msg, keyvals...)`.
### Is
`func Is(err, target error) bool`
Thin wrapper around `errors.Is`.
### Join
`func Join(errs ...error) error`
Thin wrapper around `errors.Join`.
### IsRetryable
`func IsRetryable(err error) bool`
Returns whether the first matching `*Err` in the chain is marked retryable.
### NewCodeWithRecovery
`func NewCodeWithRecovery(code, msg string, retryable bool, retryAfter *time.Duration, nextAction string) error`
Returns `&Err{Msg: msg, Code: code}` with recovery metadata attached.
### LogError
`func LogError(err error, op, msg string) error`
If `err` is nil, returns nil. Otherwise wraps the error with `Wrap(err, op, msg)`, logs `msg` through the default logger at error level with key/value pairs `"op", op, "err", err`, and returns the wrapped error.
### LogWarn
`func LogWarn(err error, op, msg string) error`
If `err` is nil, returns nil. Otherwise wraps the error with `Wrap(err, op, msg)`, logs `msg` through the default logger at warn level with key/value pairs `"op", op, "err", err`, and returns the wrapped error.
### Message
`func Message(err error) string`
Returns the `Msg` field from the first matching `*Err`. If `err` is nil, returns the empty string. For non-`*Err` errors, returns `err.Error()`.
### Must
`func Must(err error, op, msg string)`
If `err` is nil, does nothing. Otherwise logs `msg` through the default logger at error level with key/value pairs `"op", op, "err", err`, then panics with `Wrap(err, op, msg)`.
### New
`func New(opts Options) *Logger`
Constructs a logger from `opts`. It prefers a rotating writer only when `opts.Rotation` is non-nil, `opts.Rotation.Filename` is non-empty, and `RotationWriterFactory` is set; otherwise it uses `opts.Output`. If neither path yields a writer, it falls back to `os.Stderr`.
### NewCode
`func NewCode(code, msg string) error`
Returns `&Err{Msg: msg, Code: code}` as an `error`.
### RecoveryAction
`func RecoveryAction(err error) string`
Returns the first next-action hint from the error chain.
### RetryAfter
`func RetryAfter(err error) (*time.Duration, bool)`
Returns the first retry-after hint from the error chain, if present.
### NewError
`func NewError(text string) error`
Thin wrapper around `errors.New`.
### Op
`func Op(err error) string`
If `err` contains an `*Err`, returns its `Op`. Otherwise returns the empty string.
### Root
`func Root(err error) error`
Repeatedly unwraps `err` with `errors.Unwrap` until no further wrapped error exists, then returns the last error in that chain. If `err` is nil, returns nil.
### Security
`func Security(msg string, keyvals ...any)`
Calls `Default().Security(msg, keyvals...)`.
### SetDefault
`func SetDefault(l *Logger)`
Replaces the package-level default logger with `l`.
### SetLevel
`func SetLevel(level Level)`
Calls `Default().SetLevel(level)`.
### SetRedactKeys
`func SetRedactKeys(keys ...string)`
Calls `Default().SetRedactKeys(keys...)`.
### StackTrace
`func StackTrace(err error) []string`
Collects `AllOps(err)` into a slice in outermost-to-innermost order. When no operations are found, the returned slice is nil.
### Username
`func Username() string`
Returns the current username by trying `user.Current()` first, then the `USER` environment variable, then the `USERNAME` environment variable.
### Warn
`func Warn(msg string, keyvals ...any)`
Calls `Default().Warn(msg, keyvals...)`.
### Wrap
`func Wrap(err error, op, msg string) error`
If `err` is nil, returns nil. Otherwise returns a new `*Err` containing `op`, `msg`, and `err`. If the wrapped error chain already contains an `*Err` with a non-empty `Code`, the new wrapper copies that code.
### WrapCodeWithRecovery
`func WrapCodeWithRecovery(err error, code, op, msg string, retryable bool, retryAfter *time.Duration, nextAction string) error`
Returns nil only when both `err` is nil and `code` is empty. Otherwise it
returns a wrapped `*Err` with explicit recovery metadata attached.
### WrapCode
`func WrapCode(err error, code, op, msg string) error`
Returns nil only when both `err` is nil and `code` is empty. In every other case it returns `&Err{Op: op, Msg: msg, Err: err, Code: code}` as an `error`.
### WrapWithRecovery
`func WrapWithRecovery(err error, op, msg string, retryable bool, retryAfter *time.Duration, nextAction string) error`
Returns nil when `err` is nil. Otherwise it returns a wrapped `*Err` with explicit recovery metadata attached.