-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
80 lines (67 loc) · 1.84 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package logger
import (
"log"
"net/http"
"net/http/httputil"
"os"
"strconv"
"strings"
)
type Logger interface {
Printf(format string, v ...interface{})
}
type nopLogger struct{}
func (l *nopLogger) Printf(format string, v ...interface{}) {}
type defaultLogger struct {
logger *log.Logger
Verbose bool
}
func (l *defaultLogger) Printf(format string, v ...interface{}) {
trimedF := strings.TrimSpace(format)
if (strings.HasPrefix(trimedF, "[DEBUG]") || strings.HasPrefix(trimedF, "[TRACE]")) && !l.Verbose {
return
}
l.logger.Printf(format, v...)
}
func GetDefaultLogger(loggerPrefix string) Logger {
loggingEnabled, _ := strconv.ParseBool(os.Getenv("ZSCALER_SDK_LOG"))
if !loggingEnabled {
return &nopLogger{}
}
verbose, _ := strconv.ParseBool(os.Getenv("ZSCALER_SDK_VERBOSE"))
return &defaultLogger{
logger: log.New(os.Stdout, loggerPrefix, log.LstdFlags|log.Lshortfile),
Verbose: verbose,
}
}
const (
logReqMsg = `[DEBUG] Request "%s %s" details:
---[ ZSCALER SDK REQUEST ]-------------------------------
%s
---------------------------------------------------------`
logRespMsg = `[DEBUG] Response "%s %s" details:
---[ ZSCALER SDK RESPONSE ]--------------------------------
%s
-------------------------------------------------------`
)
func WriteLog(logger Logger, format string, args ...interface{}) {
if logger != nil {
logger.Printf(format, args...)
}
}
func LogRequest(logger Logger, req *http.Request) {
if logger != nil && req != nil {
out, err := httputil.DumpRequestOut(req, true)
if err == nil {
WriteLog(logger, logReqMsg, req.Method, req.URL, string(out))
}
}
}
func LogResponse(logger Logger, resp *http.Response) {
if logger != nil && resp != nil {
out, err := httputil.DumpResponse(resp, true)
if err == nil {
WriteLog(logger, logRespMsg, resp.Request.Method, resp.Request.URL, string(out))
}
}
}