dpcyx08288 2018-02-25 15:05
浏览 25
已采纳

登录到stdout并获取堆栈跟踪的字符串值

I have a logger that logs stack traces to stdout. I want to get the stack trace that was logged into a string value so I can send it as a debug email.

Here is my current code:

func (l *Logger) withStack(writer io.Writer, err error) error {
    err = errors.WithStack(err)
    fmt.Fprintf(writer, "%+v
", 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`.
}

But if the stdout stack trace looks like this:

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

...then the result of err.Error() in the email is just foo.

I guess that makes sense, because the error itself only contains foo and not the stack trace itself, but how can I get the exact stack trace as a string value?

  • 写回答

1条回答 默认 最新

  • dsfdf854456 2018-02-25 15:55
    关注

    withStack doesn't log to stdout: it logs to whatever implementation of io.Writer you provide it with. To easily get a string, consider passing it a bytes.Buffer.

    Your Error func could look like this:

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办