- Go 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| example | ||
| .golangci.yaml | ||
| errors.go | ||
| fatal.go | ||
| go.mod | ||
| go.sum | ||
| LICENSE.txt | ||
| README.md | ||
| trace.go | ||
| trace_test.go | ||
Error Tracer
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 ofruntime.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.