This function is based on sfate's gist and has been extended to dump the json string into a file instead to the stdout
Last active
July 22, 2024 20:38
-
-
Save amaddio/15f44de58712251870bcdd13e4423125 to your computer and use it in GitHub Desktop.
pretty print go object to a file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package internal | |
import ( | |
"encoding/json" | |
"fmt" | |
"os" | |
"runtime" | |
"time" | |
) | |
func prettyPrintToFile(fileName string, args ...interface{}) { | |
if fileName == "" { | |
fileName = "debug-" + time.Now().Format("2006-01-02-15-04-05") + ".txt" | |
} | |
f, fileErr := os.Create("debugFilename") | |
if fileErr != nil { | |
fmt.Println(fileErr) | |
return | |
} | |
prettyPrint(f, args) | |
} | |
func prettyPrintToStdOut(args ...interface{}) { | |
prettyPrint(os.Stdout, args) | |
} | |
func prettyPrintToStdErr(args ...interface{}) { | |
prettyPrint(os.Stdout, args) | |
} | |
func prettyPrint(w io.Writer, 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.Fprintf(w, "\n%s%s\n", prefix, caller) | |
if len(args) == 2 { | |
label := args[0] | |
value := args[1] | |
s, _ := json.MarshalIndent(value, "", "\t") | |
fmt.Fprintf(w, "%s%s: %s\n", prefix, label, string(s)) | |
} else { | |
s, _ := json.MarshalIndent(args, "", "\t") | |
fmt.Fprintf(w, "%s%s\n", prefix, string(s)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment