alog

package module
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 14, 2021 License: MIT Imports: 19 Imported by: 2

README

alog

Github-Actions

An Error-Tracker with Logger in Golang. 给你的Go补充一套错误追踪机制。

背景

1. 它可以做什么?

帮你将函数抛出的异常“串连”起来,添加代码定位、上下文变量等功能。经过简单配置,即可直通 sentry .

2. 它的应用场景是什么?

最典型的场景是 Web应用,特别是 gin框架 所构建的应用。

当然,如你也可以在非Web上下文环境中使用它。

3. 它为什么叫这个名字?

因为在预想场景中,本库的出现频率可能仅次于if err!=nil,所以本库(以及其中的部分函数、类型)起名时以尽可能「简单、独特、好按」为原则。

用法

1. 普通地捕获错误

你应当在每一级处理错误时都加入alog.CE这个函数:

func SomeFunction(ctx context.Context) error {
	if err != nil {
		alog.CE(ctx, err, alog.V{"你需要记录的变量": "你需要记录的值"})  // 这里!
		return err
	}
	return nil
}
2. 重要:ctx里要有Tracker对象

请使用我包装好的方法:

func SomeFunction() error {
	ctx, cancel := WithTracker(context.Background())
    defer cancel()   // 一定要cancel!要养成习惯!

    if err != nil {
		alog.CE(ctx, err, alog.V{"你需要记录的变量": "你需要记录的值"})
		return err
	}
	return nil
}

当然,context里没有Tracker也行,那么错误会直接打在日志上。

3. 捷径:直接装入gin中间件
func main() {
	g := gin.New()
	g.Use(alog.GinWithLogger(), alog.GinWithTracker(), alog.GinWithRecover())  // 注意顺序!
}
4. 可选:初始化!
func main() {
    alog.InitAlog("v1.0.0", "https://...", "812793r713452d")  // 记得初始化!填入Sentry相关参数。
}

如果没有初始化Sentry相关配置,则仅仅在本地打印出错误日志。一般在开发阶段这样做。

5. 在非gin上下文中使用
func anythingElse() {
    ctx, cancel := alog.WithTracker(context.Background())  // 仿context包风格
    defer cancel()
    defer alog.CERecover(ctx, V{"data": "你想要追踪的变量"})  // 会帮你recover
    panic(errors.New("我是一个异常!"))
}

TIPS: 在panic情况下,只最多追踪6层调用栈。

6. 更多

请参考测试用例,或者直接读源码,并不难。

Documentation

Index

Constants

View Source
const (
	KeyTracker            = "_alog_Tracker"
	KeyTrackID            = "_alog_TrackID"
	GinHttpResponseHeader = "X-Track"
)

Variables

View Source
var (
	ConfigAppVersion      = ""
	ConfigSentryUrl       = ""
	ConfigSentryPublicKey = ""
)
View Source
var ERROR = log.New(os.Stdout, "[ERROR]", log.LstdFlags|log.Lshortfile)
View Source
var RECOVER = log.New(os.Stdout, "[RECOVER]", log.LstdFlags|log.Lshortfile)

Functions

func BuildAndSendSentryEvent

func BuildAndSendSentryEvent(tracker *Tracker)

func BuildSentryEvent

func BuildSentryEvent(tracker *Tracker) *sentry.Event

func CE

func CE(ctx context.Context, err error, trackValues ...map[string]interface{})

CE 意思是 CheckError ,为了方便按键而起这个名字。

func CEI added in v0.3.0

func CEI(ctx context.Context, err interface{}, trackValues ...map[string]interface{})

CEI 意思是 Check Error Interface,可以灵活处理interface{}。 建议不要用在 recover() 的情况,会丢失 panic() 的位置,请使用 CERecover 替代。 建议不要使用可比较值,否则可能与其他错误栈混在一起,最好用指针或者接口变量。

func CERecover added in v0.4.0

func CERecover(ctx context.Context, trackValues ...map[string]interface{})

func CERecoverError added in v0.6.0

func CERecoverError(ctx context.Context, errPointer *error, trackValues ...map[string]interface{})

func CheckContext

func CheckContext(ctx context.Context)

func CheckTracker

func CheckTracker(tracker *Tracker)

func GetTrackID

func GetTrackID(ctx context.Context) string

func GinWithLogger

func GinWithLogger() gin.HandlerFunc

GinWithLogger returns gin.HandlerFunc, it should be used as a middleware. Compare to gin.Logger(), it prints "TrackerID" for each request in addition.

func GinWithRecover

func GinWithRecover() gin.HandlerFunc

GinWithRecover returns gin.HandlerFunc, it should be used as a middleware. It recovers your server from panic, and record the error in Tracker (to handle it later).

func GinWithTracker

func GinWithTracker() gin.HandlerFunc

GinWithTracker returns gin.HandlerFunc, it should be used as a middleware. It injects a Tracker to *gin.Context for each request.

func InitAlog

func InitAlog(
	version string,
	sentryUrl, sentryPublicKey string,
)

func RandomBytes

func RandomBytes(length int) []byte

RandomBytes Generates random alphanumeric bytes.

func Recover deprecated

func Recover(ctx context.Context)

Deprecated: 推荐使用 CERecover 或者 CERecoverError Recover

func SendSentryEvent

func SendSentryEvent(event *sentry.Event) error

func TraceStack

func TraceStack(ctx context.Context, e interface{}, trackValues ...map[string]interface{}) error

func WithTracker

func WithTracker(parent context.Context) (context.Context, context.CancelFunc)

Types

type Exception

type Exception struct {
	Error  error
	Stacks []*ExceptionStack
}

type ExceptionStack

type ExceptionStack struct {
	Filename string
	Package  string
	Function string
	Lineno   int
	Vars     V
}

type Tracker

type Tracker struct {
	ID         string
	Exceptions []*Exception
	Request    *sentry.Request
	// contains filtered or unexported fields
}

func GetTracker

func GetTracker(ctx context.Context) *Tracker

func NewTracker

func NewTracker() *Tracker

func (*Tracker) Print

func (t *Tracker) Print()

type V

type V map[string]interface{}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL