go.mondoo.com/cnquery@v0.0.0-20231005093811-59568235f6ea/logger/debug.go (about) 1 // Copyright (c) Mondoo, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package logger 5 6 import ( 7 "encoding/json" 8 "fmt" 9 "os" 10 11 "github.com/hokaccha/go-prettyjson" 12 "github.com/rs/zerolog/log" 13 "sigs.k8s.io/yaml" 14 ) 15 16 var DumpLocal string 17 18 // DebugJSON prints a prettified JSON of the data to CLI on debug mode 19 func DebugJSON(obj interface{}) { 20 if !log.Debug().Enabled() { 21 return 22 } 23 24 fmt.Fprintln(LogOutputWriter, PrettyJSON(obj)) 25 } 26 27 func TraceJSON(obj interface{}) { 28 if !log.Trace().Enabled() { 29 return 30 } 31 32 fmt.Fprintln(LogOutputWriter, PrettyJSON(obj)) 33 } 34 35 // PrettyJSON turns any object into its prettified json representation 36 func PrettyJSON(obj interface{}) string { 37 s, _ := prettyjson.Marshal(obj) 38 return string(s) 39 } 40 41 // DebugDumpJSON will write a JSON dump if the Debug or Trace mode is active and 42 // the DumpLocal prefix is defined. 43 func DebugDumpJSON(name string, obj interface{}) { 44 if !log.Debug().Enabled() { 45 return 46 } 47 48 if DumpLocal == "" { 49 if val, ok := os.LookupEnv("DEBUG"); ok && (val == "1" || val == "true") { 50 DumpLocal = "./mondoo-debug-" 51 } else if val, ok := os.LookupEnv("TRACE"); ok && (val == "1" || val == "true") { 52 DumpLocal = "./mondoo-debug-" 53 } else { 54 return 55 } 56 } 57 58 raw, err := json.MarshalIndent(obj, "", " ") 59 if err != nil { 60 log.Error().Err(err).Msg("failed to dump JSON") 61 } 62 63 err = os.WriteFile(DumpLocal+name+".json", []byte(raw), 0o644) 64 if err != nil { 65 log.Error().Err(err).Msg("failed to dump JSON") 66 } 67 } 68 69 // DebugDumpYAML will write a YAML dump if the Debug or Trace mode is active and 70 // the DumpLocal prefix is defined. 71 func DebugDumpYAML(name string, obj interface{}) { 72 if !log.Debug().Enabled() { 73 return 74 } 75 76 if DumpLocal == "" { 77 if val, ok := os.LookupEnv("DEBUG"); ok && (val == "1" || val == "true") { 78 DumpLocal = "./mondoo-debug-" 79 } else if val, ok := os.LookupEnv("TRACE"); ok && (val == "1" || val == "true") { 80 DumpLocal = "./mondoo-debug-" 81 } else { 82 return 83 } 84 } 85 86 raw, err := yaml.Marshal(obj) 87 if err != nil { 88 log.Error().Err(err).Msg("failed to dump YAML") 89 } 90 91 err = os.WriteFile(DumpLocal+name+".yaml", []byte(raw), 0o644) 92 if err != nil { 93 log.Error().Err(err).Msg("failed to dump JSON") 94 } 95 }