前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go错误日志设计:多行堆栈跟踪信息

Go错误日志设计:多行堆栈跟踪信息

作者头像
运维开发王义杰
发布2023-08-10 17:45:04
5850
发布2023-08-10 17:45:04
举报

在开发Go应用程序时,错误处理和日志记录是至关重要的任务。堆栈跟踪信息能帮助我们追踪到错误的源头,但是在默认设置下,Go的错误日志(包括堆栈跟踪)会被打印在一行,这使得日志难以阅读。本文将指导介绍如何让Go的错误日志分多行显示,以改善可读性,类似于Java的错误堆栈跟踪。

自定义logrus日志格式

logrus库允许我们自定义日志格式。我们可以创建一个自定义的日志格式(Formatter),在这个格式中,我们可以将每一个堆栈帧打印在新的一行。

首先,我们定义一个新的Formatter结构体,并实现logrus.Formatter接口的Format方法。在这个方法中,我们首先将日志条目的基本信息(时间、级别、消息)打印出来,然后检查error字段,如果这个字段存在,并且其值是一个error类型,我们就打印出这个错误的堆栈信息。

代码语言:javascript
复制
package main

import (
  "fmt"
  "strings"
  "time"

  "github.com/pkg/errors"
  "github.com/sirupsen/logrus"
)

type CustomFormatter struct{}

func (f *CustomFormatter) Format(entry *logrus.Entry) ([]byte, error) {
  // Start with the standard log entry format: time, level, message.
  output := fmt.Sprintf("%s [%s] %s\n", entry.Time.Format(time.RFC3339), strings.ToUpper(entry.Level.String()), entry.Message)

  // If this log entry has an error field and it's an error, print its stack trace.
  if err, ok := entry.Data[logrus.ErrorKey].(error); ok {
    output += fmt.Sprintf("%+v\n", err)
  }

  return []byte(output), nil
}

func main() {
  logrus.SetFormatter(new(CustomFormatter))
  err := errors.Wrap(errors.New("this is an error"), "error occurred")
  if err != nil {
    logrus.Errorf("something wrong: %+v", err)
  }
}

运行这段代码,你会看到以下输出:

代码语言:javascript
复制
2023-07-10T12:55:47+08:00 [ERROR] something wrong: this is an error
main.main
  d:/src/golang/demo/errdemo/main.go:28
runtime.main
  C:/Program Files/Go/src/runtime/proc.go:255
runtime.goexit
  C:/Program Files/Go/src/runtime/asm_amd64.s:1581
error occurred
main.main
  d:/src/golang/demo/errdemo/main.go:28
runtime.main
  C:/Program Files/Go/src/runtime/proc.go:255
runtime.goexit
  C:/Program Files/Go/src/runtime/asm_amd64.s:1581

如您所见,每个堆栈帧都被打印在新的一行,这使得日志更易于阅读。这样我们就实现了像Java一样的多行错误堆栈跟踪信息。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2023-07-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 运维开发王义杰 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 在开发Go应用程序时,错误处理和日志记录是至关重要的任务。堆栈跟踪信息能帮助我们追踪到错误的源头,但是在默认设置下,Go的错误日志(包括堆栈跟踪)会被打印在一行,这使得日志难以阅读。本文将指导介绍如何让Go的错误日志分多行显示,以改善可读性,类似于Java的错误堆栈跟踪。
    • 自定义logrus日志格式
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档