Reduce debugging time while programming Go. Use static and stack-trace analysis to determine which func call causes the error.

Errlog: reduce debugging time while programming Go Report Card Awesome Documentation GitHub issues license

Example

Introduction

Use errlog to improve error logging and speed up debugging while you create amazing code :

  • Highlight source code
  • Detect and point out which func call is causing the fail
  • Pretty stack trace
  • No-op mode for production
  • Easy implementation, adaptable logger
  • Plug to any current project without changing you or your teammates habits
  • Plug to your current logging system
Go to
Get started
Documentation
Examples
Tweaking
Feedbacks
Contributions
License
Contributors

Get started

Install

go get github.com/snwfdhmp/errlog

Usage

Replace your if err != nil with if errlog.Debug(err) to add debugging informations.

func someFunc() {
    //...
    if errlog.Debug(err) { // will debug & pass if err != nil, will ignore if err == nil
        return
    }
}

In production, call errlog.DefaultLogger.Disable(true) to enable no-op (equivalent to if err != nil)

Tweak as you need

You can configure your own logger with the following options :

type Config struct {
    PrintFunc          func(format string, data ...interface{}) //Printer func (eg: fmt.Printf)
    LinesBefore        int  //How many lines to print *before* the error line when printing source code
    LinesAfter         int  //How many lines to print *after* the error line when printing source code
    PrintStack         bool //Shall we print stack trace ? yes/no
    PrintSource        bool //Shall we print source code along ? yes/no
    PrintError         bool //Shall we print the error of Debug(err) ? yes/no
    ExitOnDebugSuccess bool //Shall we os.Exit(1) after Debug has finished logging everything ? (doesn't happen when err is nil). Will soon be replaced by ExitFunc to enable panic-ing the current goroutine. (if you need this quick, please open an issue)
}

As we don't yet update automatically this README immediately when we add new features, this definition may be outdated. (Last update: 2019/08/07) See the struct definition in godoc.org for the up to date definition

Example

Try yourself

Name and link  Description 
Basic standard usage, quick setup
Custom guided configuration for fulfilling your needs
Disabled how to disable the logging & debugging (eg: for production use)
Failing line far away example of finding the func call that caused the error while it is lines away from the errlog.Debug call
Pretty stack trace pretty stack trace printing instead of debugging.

Just read

Basic example

Note that in the example, you will see some unuseful func. Those are made to generate additional stack trace levels for the sake of example

We're going to use this sample program :

func main() {
    fmt.Println("Program start")

    wrapingFunc() //call to our important function

    fmt.Println("Program end")
}

func wrapingFunc() {
    someBigFunction() // call some func 
}

func someBigFunction() {
    someDumbFunction() // just random calls
    someSmallFunction() // just random calls
    someDumbFunction() // just random calls

    // Here it can fail, so instead of `if err  != nil` we use `errlog.Debug(err)`
    if err := someNastyFunction(); errlog.Debug(err) {
        return
    }

    someSmallFunction() // just random calls
    someDumbFunction() // just random calls
}

func someSmallFunction() {
    _ = fmt.Sprintf("I do things !")
}

func someNastyFunction() error {
    return errors.New("I'm failing for some reason") // simulate an error
}

func someDumbFunction() bool {
    return false // just random things
}

Output

Console Output examples/basic.go

We are able to detect and point out which line is causing the error.

Custom Configuration Example

Let's see what we can do with a custom configuration.

debug := errlog.NewLogger(&errlog.Config{
    // PrintFunc is of type `func (format string, data ...interface{})`
    // so you can easily implement your own logger func.
    // In this example, logrus is used, but any other logger can be used.
    // Beware that you should add '\n' at the end of format string when printing.
    PrintFunc:          logrus.Printf,
    PrintSource:        true, //Print the failing source code
    LinesBefore:        2, //Print 2 lines before failing line
    LinesAfter:         1, //Print 1 line after failing line
    PrintError:         true, //Print the error
    PrintStack:         false, //Don't print the stack trace
    ExitOnDebugSuccess: true, //Exit if err
})

Please note: This definition may be outdated. (Last update: 2019/08/07) See the struct definition in godoc.org for the up to date definition

Output

Console Output examples/custom.go

When the failing func call is a few lines away

Even when the func call is a few lines away, there is no problem for finding it.

Output

Source Example: error earlier in the code

Documentation

Documentation can be found here : Documentation

Feedbacks

Feel free to open an issue for any feedback or suggestion.

I fix process issues quickly.

Contributions

We are happy to collaborate with you :

When submitting a PR, please apply Effective Go best practices. For more information: https://golang.org/doc/effective_go.html

License information

Click the following badge to open LICENSE information.

license

Contributors

Major

Minor fixes

Owner
Martin Joly
Tech Lead @fleex | Former CTO @ordoclic
Martin Joly
Comments
  • Windows: Debug: Errlog tried to debug the error but the stack trace seems empty

    Windows: Debug: Errlog tried to debug the error but the stack trace seems empty

    Hi there, kudos for what seems to be an interesting library! Since I am learning Go, I really want to try it out.

    On Windows .errlog/examples/basic/basic.go fails. The error I get is in subject.

    Cursory glance at the code reveals problem with parsedRes := regexpParseStack.FindAllStringSubmatch(stack, -1), where length of parsedRes is zero.

    The regexp is too ugly to understand at the first glance (and I have Perl background :) ), so I stopped my analysis there.

    Example stack trace (partial):

    goroutine 6 [running]:
    runtime/debug.Stack(0x18, 0x30, 0x30)
            c:/go/src/runtime/debug/stack.go:24 +0xa4
    github.com/snwfdhmp/errlog.parseStackTrace(0x2, 0x700200, 0xc00001e4c0, 0x8)
            c:/GitHub/errlog/regexp.go:41 +0x3e
    github.com/snwfdhmp/errlog.(*logger).Debug(0xb5c130, 0x8cfe40, 0xc000106150, 0xc000081b20)
            c:/GitHub/errlog/logger.go:87 +0x7e
    github.com/snwfdhmp/errlog.Debug(0x8cfe40, 0xc000106150, 0x3)
            c:/GitHub/errlog/errlog.go:89 +0x53
    main.(*application).home(0xc000048dc0, 0x8d6640, 0xc00012e000, 0xc00011e000)
            c:/gitlab/learn-go/snippetbox/cmd/web/handlers.go:29 +0x10f
    net/http.HandlerFunc.ServeHTTP(0xc000048dd0, 0x8d6640, 0xc00012e000, 0xc00011e000)
            c:/go/src/net/http/server.go:2007 +0x4b
    net/http.(*ServeMux).ServeHTTP(0xc00001e4c0, 0x8d6640, 0xc00012e000, 0xc00011e000)
            c:/go/src/net/http/server.go:2387 +0x1c4
    net/http.serverHandler.ServeHTTP(0xc0000e8000, 0x8d6640, 0xc00012e000, 0xc00011e000)
            c:/go/src/net/http/server.go:2802 +0xab
    net/http.(*conn).serve(0xc000069720, 0x8d6d80, 0xc000108000)
            c:/go/src/net/http/server.go:1890 +0x87c
    created by net/http.(*Server).Serve
            c:/go/src/net/http/server.go:2927 +0x395
    

    Hope this helps.

    Regards,

    Jan

  • Example doesn't work

    Example doesn't work

    The example from the README (or examples/basic) does not work. Code:

    package main
    
    import (
    	"errors"
    	"fmt"
    
    	"github.com/snwfdhmp/errlog"
    )
    
    //someSmallFunc represents any func
    func someSmallFunc() {
    	fmt.Println("I do things !")
    }
    
    //someBigFunc represents any func having to handle errors from other funcs
    func someBigFunc() {
    	someSmallFunc()
    
    	if err := someNastyFunc(); errlog.Debug(err) { //here, he want to catch an error
    		return
    	}
    
    	someSmallFunc()
    }
    
    //someNastyFunc represents any failing func
    func someNastyFunc() error {
    	return errors.New("I'm failing for no reason")
    }
    
    func main() {
    	fmt.Println("Start of the program")
    	wrappingFunc()
    	fmt.Println("End of the program")
    }
    
    func wrappingFunc() {
    	someBigFunc()
    }
    

    Output:

    Start of the program
    I do things !
    Error: I'm failing for no reason
    Errlog tried to debug the error but the stack trace seems empty. If you think this is an error, please open an issue at https://github.com/snwfdhmp/errlog/issues/new and provide us logs to investigate.
    End of the program
    

    $go env:

    set GOARCH=amd64
    set GOBIN=
    set GOCACHE=C:\Users\usr\AppData\Local\go-build
    set GOEXE=.exe
    set GOFLAGS=
    set GOHOSTARCH=amd64
    set GOHOSTOS=windows
    set GOOS=windows
    set GOPATH=C:\Users\usr\go
    set GOPROXY=
    set GORACE=
    set GOROOT=C:\Go
    set GOTMPDIR=
    set GOTOOLDIR=C:\Go\pkg\tool\windows_amd64
    set GCCGO=gccgo
    set CC=gcc
    set CXX=g++
    set CGO_ENABLED=1
    set GOMOD=C:\Users\usr\Desktop\foo\go.mod
    set CGO_CFLAGS=-g -O2
    set CGO_CPPFLAGS=
    set CGO_CXXFLAGS=-g -O2
    set CGO_FFLAGS=-g -O2
    set CGO_LDFLAGS=-g -O2
    set PKG_CONFIG=pkg-config
    set GOGCCFLAGS=-m64 -mthreads -fmessage-length=0 -fdebug-prefix-map=C:\Users\usr\AppData\Local\Temp\go-build334744426=/tmp/go-build -gno-record-gcc-switches
    
  • logger.go -> panic: runtime error: index out of range

    logger.go -> panic: runtime error: index out of range

    I wanted to try the examples/basic and run into the following panic. MacOS 10.14.2 go version go1.12 darwin/amd64

    go run main.go 
    Start of the program
    I do things !
    panic: runtime error: index out of range
    
    goroutine 1 [running]:
    github.com/snwfdhmp/errlog.(*logger).Debug(0x151eec0, 0x13445e0, 0xc000116000, 0xc000116000)
    	/Users/loow/gopath/src/github.com/snwfdhmp/errlog/logger.go:83 +0x31a
    github.com/snwfdhmp/errlog.Debug(0x13445e0, 0xc000116000, 0xc0000c9f08)
    	/Users/loow/gopath/src/github.com/snwfdhmp/errlog/errlog.go:89 +0x4d
    main.someBigFunction()
    
  • Solve the crash after adding comments

    Solve the crash after adding comments

    When I write comments after code,it will panic.I found that this error occurs because of regular expressions.This error can be resolved when I write like this.

  • Errlog tried to debug the error but the stack trace seems empty.

    Errlog tried to debug the error but the stack trace seems empty.

    Hi, I get a runtime error, when errlog.Debug(...) is called multiple times in goroutine:

    Error in main.routine: error 1
    error in /home/vetti/projects/go/test-errlog/main.go (failing line not found, stack trace says func call is at line 12)
    9: func routine(ch chan error, N int) {
    10: 	for i := 0; i < N; i++ {
    11: 		errlog.Debug(<-ch)
    12: 	}
    13: 	ch <- nil
    Error: error 2
    Errlog tried to debug the error but the stack trace seems empty. If you think this is an error, please open an issue at https://github.com/snwfdhmp/errlog/issues/new and provide us logs to investigate.
    panic: runtime error: slice bounds out of range [16:14]
    
    goroutine 19 [running]:
    github.com/snwfdhmp/errlog.parseStackTrace(0x6, 0xc000062000, 0xc0000fbfb0, 0xc0000fbf40)
    	/home/vetti/go/pkg/mod/github.com/snwfdhmp/[email protected]/regexp.go:41 +0x533
    github.com/snwfdhmp/errlog.(*logger).Debug(0x930300, 0x7649c0, 0xc000085210, 0x101)
    	/home/vetti/go/pkg/mod/github.com/snwfdhmp/[email protected]/logger.go:87 +0x77
    github.com/snwfdhmp/errlog.Debug(0x7649c0, 0xc000085210, 0x1)
    	/home/vetti/go/pkg/mod/github.com/snwfdhmp/[email protected]/errlog.go:89 +0x4c
    main.routine(0xc0000740c0, 0x3)
    	/home/vetti/projects/go/test-errlog/main.go:11 +0x62
    created by main.main
    	/home/vetti/projects/go/test-errlog/main.go:18 +0x65
    exit status 2
    

    This code reproduces this problem (playground or version 2):

    package main
    
    import (
    	"errors"
    
    	"github.com/snwfdhmp/errlog"
    )
    
    func routine(ch chan error, N int) {
    	for i := 0; i < N; i++ {
    		errlog.Debug(<-ch)
    	}
    	ch <- nil
    }
    
    func main() {
    	ch := make(chan error)
    	go routine(ch, 3)
    	ch <- errors.New("error 1")
    	ch <- errors.New("error 2")
    	ch <- errors.New("error 3")
    	<-ch
    }
    

    Why can this error occur?

  • [Feature] Allow runtime enabling/disabling of output

    [Feature] Allow runtime enabling/disabling of output

    Started through: https://www.reddit.com/r/golang/comments/bzbwrz/hackable_error_handling_package_using_stacktrace/equsunu

    Allow to enable/disable the logger output using something like

    errlog.SetActive(bool)
    // or errlog.SetLogOutput(bool)
    // or errlog.SetOutput(io.Writer / nil)
    
  • "panic: runtime error: slice bounds out of range" in "github.com/snwfdhmp/errlog.getStackTrace"

    STR

    1. Create a new folder and move into it.
    2. Create "main.go" and copy the example code into it.
    3. Open a terminal/CMD window in the folder.
    4. Run "go mod init test"
    5. Run "go run main.go"

    Result

    go: finding github.com/spf13/afero v1.2.1
    go: finding github.com/mattn/go-colorable v0.1.1
    go: finding github.com/fatih/color v1.7.0
    go: finding github.com/snwfdhmp/errlog v0.0.0-20190221162002-4ce12f64f172
    go: finding github.com/mattn/go-isatty v0.0.5
    go: finding golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223
    go: downloading github.com/snwfdhmp/errlog v0.0.0-20190221162002-4ce12f64f172
    go: downloading github.com/fatih/color v1.7.0
    go: downloading github.com/sirupsen/logrus v1.3.0
    go: downloading github.com/spf13/afero v1.2.1
    go: downloading github.com/mattn/go-colorable v0.1.1
    go: downloading github.com/mattn/go-isatty v0.0.5
    go: downloading golang.org/x/crypto v0.0.0-20180904163835-0709b304e793
    go: downloading golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223
    Start of the program
    I do things !
    panic: runtime error: slice bounds out of range
    
    goroutine 1 [running]:
    github.com/snwfdhmp/errlog.getStackTrace(0x2, 0xc000121e00, 0x4ac187, 0x8)
            /home/user/go/pkg/mod/github.com/snwfdhmp/[email protected]/regexp.go:35 +0xd5
    github.com/snwfdhmp/errlog.(*logger).Debug(0x89fd10, 0x6f5000, 0xc00008ce10, 0xc00008ce10)
            /home/user/go/pkg/mod/github.com/snwfdhmp/[email protected]/logger.go:82 +0x5e
    github.com/snwfdhmp/errlog.Debug(0x6f5000, 0xc00008ce10, 0x15)
            /home/user/go/pkg/mod/github.com/snwfdhmp/[email protected]/errlog.go:89 +0x4c
    main.someBigFunction()
            /mnt/dataDrive/err/main.go:25 +0x6b
    main.wrapingFunc()
            /mnt/dataDrive/err/main.go:19 +0x20
    main.main()
            /mnt/dataDrive/err/main.go:13 +0x66
    exit status 2
    
Golang errors with stack trace and source fragments.
Golang errors with stack trace and source fragments.

Golang Errors with Stack Trace and Source Fragments Tired of uninformative error output? Probably this will be more convenient: Example package main

Dec 17, 2022
Same as fmt.Errorf but with stack trace.

Annotation with stack trace for go1.13 Go 1.13 contains support for error wrapping. Now you can add additional information to an error by wrapping it

Dec 25, 2020
A Go package providing errors with a stack trace Read-only

Errors with a stack trace A Go package providing errors with a stack trace. Features: Based of github.com/pkg/errors with similar API, addressing many

Sep 23, 2022
Go error library with error portability over the network

cockroachdb/errors: Go errors with network portability This library aims to be used as a drop-in replacement to github.com/pkg/errors and Go's standar

Dec 29, 2022
Golang advanced error usage with stack tracing

UhOh Golang advanced error usage with stack tracing uhoh consists of 3 parts: Original error Description of error Stack trace File Function Line Usage

Mar 30, 2022
Package gostackparse parses goroutines stack traces as produced by panic() or debug.Stack() at ~300 MiB/s.

gostackparse Package gostackparse parses goroutines stack traces as produced by panic() or debug.Stack() at ~300 MiB/s. Parsing this data can be usefu

Dec 1, 2022
Error interface wrappers for Google's errdetails protobuf types, because they're handy as heck and I want to use them more

Error interface wrappers for Google's errdetails protobuf types, because they're handy as heck and I want to use them more

Nov 18, 2021
eris provides a better way to handle, trace, and log errors in Go 🎆

eris Package eris provides a better way to handle, trace, and log errors in Go. go get github.com/rotisserie/eris Why you'll want to switch to eris Us

Dec 29, 2022
First attempt to trace a shell script with Datadog's go tracer
First attempt to trace a shell script with Datadog's go tracer

dd-trace-shell First attempt to trace a shell script with Datadog's go tracer. W

Dec 17, 2021
Error tracing and annotation.

errors -- import "github.com/juju/errgo" The errors package provides a way to create and diagnose errors. It is compatible with the usual Go error idi

Nov 3, 2022
Generic error handling with panic, recover, and defer.

Generic error handling with panic, recover, and defer.

Aug 25, 2022
Simple, intuitive and effective error handling for Go

Error Handling with eluv-io/errors-go The package eluv-io/errors-go makes Go error handling simple, intuitive and effective. err := someFunctionThatCa

Jan 19, 2022
This structured Error package wraps errors with context and other info

RErr package This structured Error package wraps errors with context and other info. It can be used to enrich logging, for example with a structured l

Jan 21, 2022
Simple error handling primitives

errors Package errors provides simple error handling primitives. go get github.com/pkg/errors The traditional error handling idiom in Go is roughly ak

Dec 26, 2022
A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.
A drop-in replacement for Go errors, with some added sugar! Unwrap user-friendly messages, HTTP status code, easy wrapping with multiple error types.

Errors Errors package is a drop-in replacement of the built-in Go errors package with no external dependencies. It lets you create errors of 11 differ

Dec 6, 2022
A comprehensive error handling library for Go

Highlights The errorx library provides error implementation and error-related utilities. Library features include (but are not limited to): Stack trac

Jan 6, 2023
A Go (golang) package for representing a list of errors as a single error.

go-multierror go-multierror is a package for Go that provides a mechanism for representing a list of error values as a single error. This allows a fun

Jan 1, 2023
A flexible error support library for Go

errors Please see http://godoc.org/github.com/spacemonkeygo/errors for info License Copyright (C) 2014 Space Monkey, Inc. Licensed under the Apache Li

Nov 3, 2022
A powerful, custom error package for Go

custom-error-go A powerful, custom error package for Go Detailed explanation: https://medium.com/codealchemist/error-handling-in-go-made-more-powerful

Apr 19, 2022