Home > Back-end >  Go 1.17: How to log error with the stack trace
Go 1.17: How to log error with the stack trace

Time:04-29

How to log the line number and file name of the error? I tried %w, zap logger's Errorw, but its not working as good as github.com/pkg/errors, which is sadly archived. Here is the code:

package main

import (
    stderrors "errors"

    pkgerrors "github.com/pkg/errors"

    "go.uber.org/zap"
)

func main() {
    logger := zap.NewExample().Sugar()

    logger.Errorf("Hello %v %w", "error", stderrors.New("some error"))
    logger.Errorw("Hello", "error", stderrors.New("some error"))

    logger.Errorf("Hello %v %w", "error", pkgerrors.New("some error"))
    logger.Errorw("Hello", "error", pkgerrors.New("some error"))
}

Here is the playgroud code for the same: https://go.dev/play/p/PO3dFrK5ua6

CodePudding user response:

you can use like this,

log.New(os.Stdout, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)

CodePudding user response:

To directly answer your question: https://www.bugsnag.com/blog/go-errors

But I want to just say that it's not good practice to do this in Go. It's best to float your errors down the function calls and print them out after.

func HandleApiReq() (*APIResponse, error) {
    // ...logic...error handling
    gwres, err := QueryGateway()
    // ...logic...error handling
    return nil, fmt.Errorf("failed to process API request on endpoint %s: %v", endpoint, err)
}

func QueryGateway() (*GatewayResult, error) {
    // ...logic...error handling
    dbres, err := GetFromDB()
    // ...logic...error handling
    return nil, fmt.Errorf("error received from db in gateway %s: %v", gw.Name(), err)
}

func GetFromDb() (*DBResult, error) {
    // ...logic...error handling
    return nil, fmt.Errorf("failed to get from db. Db err received on table %s: %v", tableName err)
}

So your end output assuming your db gets an error will naturally be built from all your previous errors like: failed to process API request on endpoint /products: error received from db in gateway stock_gateway: failed to get from db. Db err received on table name products: Deadlock occurred

  •  Tags:  
  • go
  • Related