Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

  • Avoid logging directly at the site where an error is produced or returned.  Instead let the entry point to processing do the logging. If the returned error message is insufficient (often they are already sufficient) use errors.Wrap to add context to the returned error.
  • Use the github.com/pkg/errors package instead of errors, and user errors.WithStack(err) wherever an error is produced or returned from an external package. errors.WithStack produces a stack trace pointing to the line of code which produced the error, which also prevents us from having to add our own custom error message so that we can correlate the error message to the line of code which produced it.This can also be done wherever there's an errors.New, I.E errors.WithStack(errors.New("my error")).
  • Any new packages that need to log things should use the common logger specified in common/pkg/logging/logging.go. This can be used by importing in your package (in package.go, or another file)

    Code Block
    titlego mocking log example
    package newpackage
    
    import (
    	"github.com/ForgeCloud/saas/services/go/common/pkg/logging"
    )
    
    var (
    	log = logging.Recorder
    )
  • Programs should only exit in a 'main' function, and should log which error caused the program to fail at the 'Fatal' level. This will make it obvious when looking at logs where and why the program exited.

    Code Block
    titlego mocking error handling example
    func main() {
    	// ... do some setup ...
    	err := runProgramForReal()
    	if err != nil {
    		log.WithError(err).Fatal("Error while running program")
    	}
    }

...