| 1 |
package internal |
| 2 |
|
| 3 |
import ( |
| 4 |
"flag" |
| 5 |
"io" |
| 6 |
"log" |
| 7 |
"os" |
| 8 |
) |
| 9 |
|
| 10 |
func init() { |
| 11 |
flag.BoolVar(&debugMode, "debug", false, "true") |
| 12 |
} |
| 13 |
|
| 14 |
var debugMode = false |
| 15 |
var infoMode = true |
| 16 |
var debugFlags = log.Lshortfile | log.LstdFlags |
| 17 |
|
| 18 |
// DebugMode returns true if debugMode is set, false otherwise |
| 19 |
func DebugMode() bool { |
| 20 |
return debugMode |
| 21 |
} |
| 22 |
|
| 23 |
// SetDebugMode sets the debug mode |
| 24 |
func SetDebugMode(debug bool) { |
| 25 |
debugMode = debug |
| 26 |
} |
| 27 |
|
| 28 |
// InfoLog returns true if logging to info level is enabled, false otherwise |
| 29 |
func InfoLog() bool { |
| 30 |
return infoMode |
| 31 |
} |
| 32 |
|
| 33 |
// SetInfoLog sets whether the info log should be enabled |
| 34 |
func SetInfoLog(info bool) { |
| 35 |
infoMode = info |
| 36 |
} |
| 37 |
|
| 38 |
// WithDebugLogging enables debug logging for the given function fn |
| 39 |
func WithDebugLogging(fn func()) { |
| 40 |
debugMode = true |
| 41 |
fn() |
| 42 |
debugMode = false |
| 43 |
} |
| 44 |
|
| 45 |
// Debug is a logger which logs when debugMode is enabled. If disabled, it executes a noop |
| 46 |
var Debug = newConditionalLogger(os.Stderr, "go-hbci: ", debugFlags, &debugMode) |
| 47 |
|
| 48 |
// Info is a logger which logs when infoMode is enabled. If disabled, it executes a noop |
| 49 |
var Info = newConditionalLogger(os.Stderr, "go-hbci: ", log.LstdFlags, &infoMode) |
| 50 |
|
| 51 |
func newConditionalLogger(w io.Writer, prefix string, flag int, condition *bool) *log.Logger { |
| 52 |
condWriter := newConditionalWriter(w, condition) |
| 53 |
return log.New(condWriter, prefix, flag) |
| 54 |
} |
| 55 |
|
| 56 |
func newConditionalWriter(w io.Writer, condition *bool) io.Writer { |
| 57 |
return &conditionalWriter{Writer: w, condition: condition} |
| 58 |
} |
| 59 |
|
| 60 |
type conditionalWriter struct { |
| 61 |
condition *bool |
| 62 |
io.Writer |
| 63 |
} |
| 64 |
|
| 65 |
func (c *conditionalWriter) Write(p []byte) (n int, err error) { |
| 66 |
if *c.condition { |
| 67 |
return c.Writer.Write(p) |
| 68 |
} |
| 69 |
return 0, nil |
| 70 |
} |