在软件系统中定位问题时日志不可或缺,但是当一个系统功能繁多,需要打印的日志也多如牛毛,此时为了提高我们浏览日志的效率,便于阅读的输出格式必不可少。

打印结构体是打印日志时最长见的操作,但是当结构体内容较多都在一行时,不易于阅读。在 Go 中结构体可以方便的转为 JSON,因此我们可以借助 JSON 完成对 struct 的格式化输出。

打印在一行,使用 %+v 显示结构体字段名:

package main

import (
	"fmt"
)

// Student 学生信息
type Student struct {
	Name  string
	Addr  HomeInfo
	M   map[string]string
}

// HomeInfo 家庭住址
type HomeInfo struct {
	Province   string
	City     string
	County    string
	Street    string
	DetailedAddr string
}

var student = Student{
	Name: "dablelv",
	Addr: HomeInfo{
		Province:   "Guangdong",
		City:     "Shenzhen",
		County:    "Baoan",
		Street:    "Xixiang",
		DetailedAddr: "Shengtianqi",
	},
	M: map[string]string{
		"hobby": "pingpopng",
	},
}

func main() {
	fmt.Printf("student=%+v\n", student)
}

运行输出:

student={Name:cat Addr:{Province:Guangdong City:Shenzhen County:Baoan Street:Xixiang DetailedAddr:Shengtianqi} M:map[hobby:pingpopng]}

输出格式化 JSON 串:

func main() {
	bs, _ := json.Marshal(student)
	var out bytes.Buffer
	json.Indent(&out, bs, "", "\t")
	fmt.Printf("student=%v\n", out.String())
}

运行输出结果:

student={
"Name": "cat",
"Addr": {
"Province": "Guangdong",
"City": "Shenzhen",
"County": "Baoan",
"Street": "Xixiang",
"DetailedAddr": "Shengtianqi"
},
"M": {
"hobby": "pingpopng"
}
}

将 strutc 转为 json 串后再格式化输出,大大增加了可阅读性。

转换函数已经添加至个人的 Go 工具库 go-huge-util,使用示例如下:

package main

import (
	"fmt"
  huge "github.com/dablelv/go-huge-util"
)

func main() {
	s, _ := huge.ToFormattedJSON(&student)
	fmt.Printf("student=%v\n", s)
}

运行输出:

student={
"Name": "cat",
"Addr": {
"Province": "Guangdong",
"City": "Shenzhen",
"County": "Baoan",
"Street": "Xixiang",
"DetailedAddr": "Shengtianqi"
},
"M": {
"hobby": "pingpopng"
}
}

您可能感兴趣的文章: