Skip to content

Instantly share code, notes, and snippets.

@sfate
Last active January 18, 2023 17:38
Show Gist options
  • Save sfate/9d45f6c5405dc4c9bf63bf95fe6d1a7c to your computer and use it in GitHub Desktop.
Save sfate/9d45f6c5405dc4c9bf63bf95fe6d1a7c to your computer and use it in GitHub Desktop.
Pretty print objects in golang

TL;DR

Function that provides ability to print variable values in golang. No external dependencies are used. Try it online: https://go.dev/play/p/mxbwyIUSLVZ

Legend

Sometimes printing some variable value in golang might be challenging or not easy to follow. Current implementation just simply wraps passed object into json and prints it in STDOUT.

As a bonus it can print label for provided variable value to make it easier to distinguish in logs. + Line on which it was called is listed above variable value output.

Solution example

type room struct {
	Number int
	Color  string
	IsFree bool
}

func main() {
	time, _ := time.Parse("2006-01-02", "2020-05-22")
	room := &room{
		Number: 7,
		Color:  "purple",
		IsFree: true,
	}

	prettyPrint("room", room)
	prettyPrint(room.IsFree)
	prettyPrint("room number", room.Number)
	prettyPrint(time)
}

Provides following output:

[PrettyPrint] 11-10-2009 23:00:00 -- /tmp/sandbox1984072684/prog.go:51
[PrettyPrint] 11-10-2009 23:00:00 -- room: {
	"Number": 7,
	"Color": "purple",
	"IsFree": true
}

[PrettyPrint] 11-10-2009 23:00:00 -- /tmp/sandbox1984072684/prog.go:52
[PrettyPrint] 11-10-2009 23:00:00 -- [
	true
]

[PrettyPrint] 11-10-2009 23:00:00 -- /tmp/sandbox1984072684/prog.go:53
[PrettyPrint] 11-10-2009 23:00:00 -- room number: 7

[PrettyPrint] 11-10-2009 23:00:00 -- /tmp/sandbox1984072684/prog.go:54
[PrettyPrint] 11-10-2009 23:00:00 -- [
	"2020-05-22T00:00:00Z"
]
func prettyPrint(args ...interface{}) {
var caller string
timeNow := time.Now().Format("01-02-2006 15:04:05")
prefix := fmt.Sprintf("[%s] %s -- ", "PrettyPrint", timeNow)
_, fileName, fileLine, ok := runtime.Caller(1)
if ok {
caller = fmt.Sprintf("%s:%d", fileName, fileLine)
} else {
caller = ""
}
fmt.Printf("\n%s%s\n", prefix, caller)
if len(args) == 2 {
label := args[0]
value := args[1]
s, _ := json.MarshalIndent(value, "", "\t")
fmt.Printf("%s%s: %s\n", prefix, label, string(s))
} else {
s, _ := json.MarshalIndent(args, "", "\t")
fmt.Printf("%s%s\n", prefix, string(s))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment