github.com/kaisawind/go-swagger@v0.19.0/generator/debug.go (about) 1 // Copyright 2015 go-swagger maintainers 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package generator 16 17 import ( 18 "encoding/json" 19 "fmt" 20 "log" 21 "os" 22 "path/filepath" 23 "runtime" 24 ) 25 26 var ( 27 // Debug when the env var DEBUG or SWAGGER_DEBUG is not empty 28 // the generators will be very noisy about what they are doing 29 Debug = os.Getenv("DEBUG") != "" || os.Getenv("SWAGGER_DEBUG") != "" 30 // generatorLogger is a debug logger for this package 31 generatorLogger *log.Logger 32 ) 33 34 func init() { 35 debugOptions() 36 } 37 38 func debugOptions() { 39 generatorLogger = log.New(os.Stdout, "generator:", log.LstdFlags) 40 } 41 42 // debugLog wraps log.Printf with a debug-specific logger 43 func debugLog(frmt string, args ...interface{}) { 44 if Debug { 45 _, file, pos, _ := runtime.Caller(1) 46 generatorLogger.Printf("%s:%d: %s", filepath.Base(file), pos, 47 fmt.Sprintf(frmt, args...)) 48 } 49 } 50 51 // debugLogAsJSON unmarshals its last arg as pretty JSON 52 func debugLogAsJSON(frmt string, args ...interface{}) { 53 if Debug { 54 var dfrmt string 55 _, file, pos, _ := runtime.Caller(1) 56 dargs := make([]interface{}, 0, len(args)+2) 57 dargs = append(dargs, filepath.Base(file), pos) 58 if len(args) > 0 { 59 dfrmt = "%s:%d: " + frmt + "\n%s" 60 bbb, _ := json.MarshalIndent(args[len(args)-1], "", " ") 61 dargs = append(dargs, args[0:len(args)-1]...) 62 dargs = append(dargs, string(bbb)) 63 } else { 64 dfrmt = "%s:%d: " + frmt 65 } 66 generatorLogger.Printf(dfrmt, dargs...) 67 } 68 }