github.com/AngusLu/go-swagger@v0.28.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 debugOptions() {
    35  	generatorLogger = log.New(os.Stdout, "generator:", log.LstdFlags)
    36  }
    37  
    38  // debugLog wraps log.Printf with a debug-specific logger
    39  func debugLog(frmt string, args ...interface{}) {
    40  	if Debug {
    41  		_, file, pos, _ := runtime.Caller(1)
    42  		generatorLogger.Printf("%s:%d: %s", filepath.Base(file), pos,
    43  			fmt.Sprintf(frmt, args...))
    44  	}
    45  }
    46  
    47  // debugLogAsJSON unmarshals its last arg as pretty JSON
    48  func debugLogAsJSON(frmt string, args ...interface{}) {
    49  	if Debug {
    50  		var dfrmt string
    51  		_, file, pos, _ := runtime.Caller(1)
    52  		dargs := make([]interface{}, 0, len(args)+2)
    53  		dargs = append(dargs, filepath.Base(file), pos)
    54  		if len(args) > 0 {
    55  			dfrmt = "%s:%d: " + frmt + "\n%s"
    56  			bbb, _ := json.MarshalIndent(args[len(args)-1], "", " ")
    57  			dargs = append(dargs, args[0:len(args)-1]...)
    58  			dargs = append(dargs, string(bbb))
    59  		} else {
    60  			dfrmt = "%s:%d: " + frmt
    61  		}
    62  		generatorLogger.Printf(dfrmt, dargs...)
    63  	}
    64  }