概览

在调试 golang 程序时,加断点查看变量值固然是一种方法,但更多的时候只是简单的加个 log 看一下。

可以 fmt.Printf("%+v", xxx), 如果想查看 json 还要转换,很麻烦。

于是,我封装了一个简便的 debuglog 库,用于 debug 变量。

详见 https://github.com/chinaran/debuglog

  • debuglog.Val(): 打印变量
  • debuglog.SpewVal(): 使用 spew 库打印变量(可以详细看到结构体每个字段的定义和值)
  • debuglog.ToJson(): 转成 json 字符串打印
  • debuglog.ToJsonPretty(): 有缩进和换行的 json 字符串

调试好程序解决 bug 后,删掉所有的 debuglog 即可。

示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import "github.com/chinaran/debuglog"

type TestJson struct {
	Id   int64
	Name string
}

func main() {
	intVal := 123
	debuglog.Val(intVal)
	debuglog.Val(intVal, "prefix1")
	debuglog.Val(intVal, "prefix1", "prefix2")

	testJson := TestJson{Id: 987, Name: "alan"}

	debuglog.SpewVal(testJson, "testJson Spew")
	// debuglog.OctUtf8Val(testJson, "testJson")

	debuglog.ToJson(testJson, "testJson")
	debuglog.ToJsonPretty(testJson, "testJson Pretty")
}

示例结果

示例结果