【问题标题】:Why don't I see fmt logs in my terminal when running go app locally?为什么我在本地运行 go app 时在我的终端中看不到 fmt 日志?
【发布时间】:2022-01-27 23:32:23
【问题描述】:

我正在尝试调试我的 golang 应用程序。目前,我有一个不起作用的 API 请求,其中包含这行代码: fmt.Errorf("Object(%q).CopierFrom(%q).Run: %v", dstName, object, err)

如何查看此错误日志的输出?如果不可能,还有什么其他方法可以调试? (运行时调用会很好)

【问题讨论】:

  • 如果你想记录错误,你必须记录它。 fmt.Errorf 只是创建一个错误对象。错误没有输出。
  • 如果您使用一些实际代码更新您的问题,提供具体建议会更容易。但也许你想打电话给fmt.Printflog.Error 或类似的东西。

标签: go fmt


【解决方案1】:

fmt.Errorf() 创建一个错误对象。但不能打印。doc

如果您只是想将消息打印到标准输出: run

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"}

【讨论】:

    【解决方案2】:

    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)
    

    【讨论】:

      【解决方案3】:

      fmt.Errorf 创建一个错误 - 非常适合函数返回 - 但它不会被隐式记录。

      如果您只想简单地记录错误:

      log.Printf("api X: error %v", err)
      

      【讨论】:

        【解决方案4】:

        最好在使用任何函数之前阅读函数签名和 cmets。

        // 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 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-07-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多