go - 记录到标准输出并获取堆栈跟踪的字符串值

标签 go

我有一个记录器,可以将堆栈跟踪记录到 stdout。我想获取记录到字符串值中的堆栈跟踪,以便我可以将其作为调试电子邮件发送。

这是我当前的代码:

func (l *Logger) withStack(writer io.Writer, err error) error {
    err = errors.WithStack(err)
    fmt.Fprintf(writer, "%+v\n", err)
    return err
}

func (l *Logger) Error(err error) error {
    // Logs stack trace to `stdout`...
    l.withStack(os.Stdout, err)

    // Here I want to get the string value of what was logged to `stdout`.
}

但是如果 stdout 堆栈跟踪看起来像这样:

foo
infrastructure/logger.(*Logger).withStack
    /Users/lansana/Projects/Go/src/app/src/infrastructure/logger/logger.go:40
infrastructure/logger.(*Logger).Error
    /Users/lansana/Projects/Go/src/app/src/infrastructure/logger/logger.go:50
main.main
    /Users/lansana/Projects/Go/src/app/src/microservices/api/main.go:44
runtime.main
    /usr/local/Cellar/go/1.9/libexec/src/runtime/proc.go:185
runtime.goexit
    /usr/local/Cellar/go/1.9/libexec/src/runtime/asm_amd64.s:2337

...那么电子邮件中 ​​err.Error() 的结果就是 foo

我想这是有道理的,因为错误本身只包含 foo 而不是堆栈跟踪本身,但是我怎样才能得到准确的堆栈跟踪作为字符串值?

最佳答案

withStack 不会记录到标准输出:它会记录到您为其提供的 io.Writer 的任何实现。要轻松获取字符串,请考虑将其传递给 bytes.Buffer

您的 Error 函数可能如下所示:

func sendErrorMail(s string) error {
    // Send the stack trace `s` by email
}

func (l *Logger) Error(err error) {
    // Get the stack trace as a string
    buf := new(bytes.Buffer)
    l.withStack(buf, err)

    sendErrorMail(buf.String())
}

Simple demonstration of this idea as a playground .

关于go - 记录到标准输出并获取堆栈跟踪的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48974934/

相关文章:

go - 无效的接收器类型 []T([]T 是未命名的类型)解决方法?

go - GC 如何在没有单独的运行时或 VM 的情况下工作?

go - 如何使用 "internal"包?

json - Golang 空类型和 json.Decode()

go - 如何查看程序中是否运行了GoLand调试器?

go - 将 .gz 文件添加到 tar.gz 文件,但在添加之前解码 gz。输出文件被剪切(损坏)

go - 如何处理 Go 包中嵌套的 "vendor"目录?

arrays - 在函数参数中接收任何数组类型

amazon-web-services - 运行 AWS Golang Lambda 时出现 exec 格式错误

java - 如何将这个 Java 正则表达式转换为 Go 的正则表达式语法?