'Go 1.17: How to log error with the stack trace

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

go


Solution 1:[1]

you can use like this,

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 code philosopher
Solution 2 zkscpqm