No description
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-09-29 15:18:09 +02:00
example Merge branch 'master' into upstream 2024-10-01 23:40:11 +02:00
.golangci.yaml first POC 2024-08-15 09:57:47 +02:00
errors.go add: license to new files 2024-09-03 17:14:06 +02:00
fatal.go fix: report origin/stack paths relative to cwd, not absolute 2026-09-01 17:45:48 +02:00
go.mod go: update dependencies 2026-09-01 14:35:09 +02:00
go.sum go: update dependencies 2026-09-01 14:35:09 +02:00
LICENSE.txt add: license 2024-08-16 09:08:57 +02:00
README.md doc: add examples 2026-09-29 15:18:09 +02:00
trace.go fix: report origin/stack paths relative to cwd, not absolute 2026-09-01 17:45:48 +02:00
trace_test.go doc: add examples 2026-09-29 15:18:09 +02:00

Error Tracer

Go Reference

Sometimes you need to trace the origin, and call-path of errors, which basically is a stacktrace as soon as the error appears to the caller of the application (or its logging system).

It is meant as a near drop-in replacement for the standard errors package: New, Is, As, Join and Unwrap are simply redirected to their errors package counterparts, and Errorf behaves like fmt.Errorf. The difference is that every error created or wrapped by this package remembers the call stack at the point it was created, so you can print it later.

Installation

go get go.schlittermann.de/heiko/trace

Usage

import trace "go.schlittermann.de/heiko/trace"

func foo() error {
	return trace.New("foo failed")
}

func bar() error {
	// Wrap attaches the call trace to any existing error; nil stays nil.
	return trace.Wrap(foo())
}

func main() {
	if err := bar(); err != nil {
		log.Println(err) // by default: "foo failed", no trace
	}
}

By default Error() only returns the wrapped error's message, so a traced error is safe to log like any other error. Tracing information is added on demand via the package variables (or the equivalent environment variables / command line flags below):

  • trace.Origin (TRACE_ORIGIN) - append the file and line where the error was created.
  • trace.Stack (TRACE) - append the full call stack instead of just the origin.
  • trace.Disabled (TRACE_DISABLE) - turn off tracing entirely; errors behave as plain errors and no call stack is captured, which avoids the (small) overhead of runtime.Callers.
  • trace.Depth - how many stack frames to capture (default: 50).

Applications that want these controllable via command line flags can call trace.Flags, which registers -<prefix>disable, -<prefix>origin, -<prefix>full and -<prefix>depth:

trace.Flags("trace.", nil) // registers -trace.disable, -trace.origin, -trace.full, -trace.depth
flag.Parse()

trace.Fatal is a drop-in replacement for log.Fatal that additionally logs the caller's function, file and line when Origin or Stack is enabled.

See example/main.go for a runnable demonstration.

License

The License is here, because I created this package using my private resources.