我正在嘗試除錯我的 golang 應用程式。目前,我有一個無效的 API 請求,其中包含以下代碼行:
fmt.Errorf("Object(%q).CopierFrom(%q).Run: %v", dstName, object, err)
如何查看此錯誤日志的輸出?如果不可能的話,還有哪些其他方法可以在 go 中進行除錯?(運行時呼叫會很好)
uj5u.com熱心網友回復:
fmt.Errorf()創建一個錯誤物件。但不能列印。檔案
如果您只是想將訊息列印到標準輸出: 運行
package main
import (
"fmt"
)
func main() {
const name, id = "bueller", 17
err := fmt.Errorf("user %q (id %d) not found", name, id)
fmt.Println(err.Error())
}
出去:
user "bueller" (id 17) not found
如果你想除錯 golang 代碼,我建議使用日志包,例如: zerolog
package main
import (
"errors"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
func main() {
// UNIX Time is faster and smaller than most timestamps
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
err := errors.New("seems we have an error here")
log.Error().Err(err).Msg("this is an error")
}
出去:
{"level":"error","error":"seems we have an error here","time":1640795128,"message":"this is an error"}
uj5u.com熱心網友回復:
fmt.Errorf創建一個error物件;它不列印。
從檔案中fmt.Errorf:
func Errorf(format string, a ...interface{}) error
如果您只是想將訊息列印到標準輸出:
fmt.Printf("Object(%q).CopierFrom(%q).Run: %v\n", dstName, object, err)
如果你想寫入錯誤日志,我建議查看log包。例如,如果您想寫入 stderr:
logger := log.New(os.Stderr, "my-app", 0)
logger.Printf("Object(%q).CopierFrom(%q).Run: %v", dstName, object, err)
uj5u.com熱心網友回復:
fmt.Errorf 創建一個錯誤 - 函式回傳的理想選擇 - 但它不會被隱式記錄。
如果你想簡單地記錄一個錯誤:
log.Printf("api X: error %v", err)
uj5u.com熱心網友回復:
在使用任何函式之前,最好先閱讀函式簽名和注釋。
// Errorf formats according to a format specifier and returns the string as a
// value that satisfies error.
//
// If the format specifier includes a %w verb with an error operand,
// the returned error will implement an Unwrap method returning the operand. It is
// invalid to include more than one %w verb or to supply it with an operand
// that does not implement the error interface. The %w verb is otherwise
// a synonym for %v.
func Errorf(format string, a ...interface{}) error
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400781.html
上一篇:簡單的godoc你好世界
下一篇:如何將兩個回傳引數合并為一個值
