在Golang应用程序中记录堆栈跟踪信息的方法

141 阅读1分钟

你可以使用下面的包来记录特定动作被触发的堆栈跟踪信息。例如,触发一个恐慌或记录一个消息:

package stacktrace

import (
	"fmt"
	"os"
	"runtime"
	"strings"
)

type StackTrace struct {
	msg  string
	path string
}

// New function constructs a new `StackTrace` struct by using given panic
// message, absolute path of the caller file and the line number.
func New(msg string) *StackTrace {
	_, file, line, _ := runtime.Caller(1)
	p, _ := os.Getwd()

	return &StackTrace{
		msg:  msg,
		path: fmt.Sprintf("%s:%d", strings.TrimPrefix(file, p), line),
	}
}

func (s *StackTrace) Message() string {
	return s.msg
}

func (s *StackTrace) Path() string {
	return s.path
}

用法

// Somewhere in the controller.go
st := stacktrace.New("Hello")
log.Printf("%s\n", st)

输出

2019/12/26 00:38:47 &{Hello /internal/home/controller.go:24}