-
Notifications
You must be signed in to change notification settings - Fork 13
/
logger.go
249 lines (214 loc) · 6.04 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package platformclientv2
import (
"encoding/json"
"fmt"
"github.com/tidwall/pretty"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
var (
traceLogger *log.Logger
debugLogger *log.Logger
errorLogger *log.Logger
)
type LoggingLevel int
const (
LTrace LoggingLevel = iota
LDebug
LError
LNone
)
type LoggingFormat int
const (
JSON LoggingFormat = iota
Text
)
func loggingFormatFromString(value string) *LoggingFormat {
var logFormat LoggingFormat
switch value {
case "text":
logFormat = Text
case "json":
logFormat = JSON
default:
return nil
}
return &logFormat
}
func loggingLevelFromString(value string) *LoggingLevel {
var logLevel LoggingLevel
switch value {
case "trace":
logLevel = LTrace
case "debug":
logLevel = LDebug
case "error":
logLevel = LError
case "none":
logLevel = LNone
default:
return nil
}
return &logLevel
}
type logStatement struct {
Date *time.Time `json:"date,omitempty"`
Level string `json:"level,omitempty"`
Method string `json:"method,omitempty"`
URL string `json:"url,omitempty"`
RequestHeaders http.Header `json:"requestHeaders,omitempty"`
ResponseHeaders http.Header `json:"responseHeaders,omitempty"`
CorrelationId string `json:"correlationId,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
RequestBody string `json:"requestBody,omitempty"`
ResponseBody string `json:"responseBody,omitempty"`
}
func (s *logStatement) string(format LoggingFormat, logRequestBody, logResponseBody bool) string {
if len(s.RequestHeaders["Authorization"]) > 0 {
s.RequestHeaders["Authorization"] = []string{"[REDACTED]"}
}
if !logRequestBody {
s.RequestBody = ""
}
if !logResponseBody {
s.ResponseBody = ""
}
if format == Text {
return fmt.Sprintf(`
=== REQUEST ===%v%v%v%v
=== RESPONSE ===%v%v%v%v`,
formatValue("URL", s.URL),
formatValue("Method", s.Method),
formatValue("Headers", formatHeaders(s.RequestHeaders)),
formatValue("Body", s.RequestBody),
formatValue("Status", fmt.Sprintf("%v", s.StatusCode)),
formatValue("Headers", formatHeaders(s.ResponseHeaders)),
formatValue("CorrelationId", s.CorrelationId),
formatValue("Body", s.ResponseBody))
}
j, _ := json.Marshal(s)
str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\u`, `\u`, -1))
return strings.TrimRight(string(pretty.Ugly([]byte(str))), "\n")
}
func (c *LoggingConfiguration) configureLogging() {
var f *os.File
if c.logFilePath != "" {
f, _ = os.OpenFile(c.logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
}
var stdoutWrt io.Writer
var stderrWrt io.Writer
if f != nil && c.logToConsole { // Logging to console and file
stdoutWrt = io.MultiWriter(f, os.Stdout)
stderrWrt = io.MultiWriter(f, os.Stderr)
} else if f == nil && c.logToConsole { // Logging to console
stdoutWrt = io.MultiWriter(os.Stdout)
stderrWrt = io.MultiWriter(os.Stderr)
} else if f != nil && !c.logToConsole { // Logging to file
stdoutWrt = io.MultiWriter(f)
stderrWrt = io.MultiWriter(f)
} else { // Cannot log to anything
traceLogger = nil
debugLogger = nil
errorLogger = nil
return
}
flags := 0
tracePrefix := ""
debugPrefix := ""
errorPrefix := ""
if c.logFormat == Text {
flags = log.Ldate | log.Ltime
tracePrefix = "TRACE: "
debugPrefix = "DEBUG: "
errorPrefix = "ERROR: "
}
traceLogger = log.New(stdoutWrt, tracePrefix, flags)
debugLogger = log.New(stdoutWrt, debugPrefix, flags)
errorLogger = log.New(stderrWrt, errorPrefix, flags)
}
func (c *LoggingConfiguration) trace(method, URL string, requestBody []byte, statusCode int, requestHeaders, responseHeaders http.Header) {
now := time.Now()
logStatement := &logStatement{
Date: &now,
Level: "trace",
Method: method,
URL: URL,
RequestBody: string(requestBody),
CorrelationId: getCorrelationId(responseHeaders),
StatusCode: statusCode,
RequestHeaders: requestHeaders,
ResponseHeaders: responseHeaders,
}
c.log(traceLogger, LTrace, logStatement.string(c.logFormat, c.LogRequestBody, c.LogResponseBody))
}
func (c *LoggingConfiguration) debug(method, URL string, requestBody []byte, statusCode int, requestHeaders http.Header) {
now := time.Now()
logStatement := &logStatement{
Date: &now,
Level: "debug",
Method: method,
URL: URL,
RequestBody: string(requestBody),
StatusCode: statusCode,
RequestHeaders: requestHeaders,
}
c.log(debugLogger, LDebug, logStatement.string(c.logFormat, c.LogRequestBody, c.LogResponseBody))
}
func (c *LoggingConfiguration) error(method, URL string, requestBody, responseBody []byte, statusCode int, requestHeaders, responseHeaders http.Header) {
now := time.Now()
logStatement := &logStatement{
&now,
"error",
method,
URL,
requestHeaders,
responseHeaders,
getCorrelationId(responseHeaders),
statusCode,
string(requestBody),
string(responseBody),
}
c.log(errorLogger, LError, logStatement.string(c.logFormat, c.LogRequestBody, c.LogResponseBody))
}
func (c *LoggingConfiguration) log(logger *log.Logger, logLevel LoggingLevel, v ...interface{}) {
if logLevel >= c.LogLevel && logger != nil {
logger.Println(v...)
}
}
func getCorrelationId(headers http.Header) string {
for key, values := range headers {
if strings.ToLower(key) == "inin-correlation-id" {
for _, value := range values {
if value != "" {
return value
}
}
}
}
return ""
}
// Returns each header key value pair indented by one tab
func formatHeaders(headers http.Header) string {
var result string
for key, values := range headers {
var valuesString string
for _, value := range values {
valuesString = fmt.Sprintf("%v, %v", valuesString, value)
}
valuesString = strings.TrimLeft(valuesString, ", ")
result = fmt.Sprintf("%v\n\t%v: %v", result, key, valuesString)
}
return result
}
// Used to only print values that aren't empty
func formatValue(name, value string) string {
if value != "" {
return fmt.Sprintf("\n%v: %v", name, value)
}
return ""
}