forked from TV4/logrus-stackdriver-formatter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
formatter.go
272 lines (235 loc) · 7.49 KB
/
formatter.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package stackdriver
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"github.com/go-stack/stack"
"github.com/sirupsen/logrus"
)
var skipTimestamp bool
type severity string
const (
severityDebug severity = "DEBUG"
severityInfo severity = "INFO"
severityWarning severity = "WARNING"
severityError severity = "ERROR"
severityCritical severity = "CRITICAL"
severityAlert severity = "ALERT"
)
var levelsToSeverity = map[logrus.Level]severity{
logrus.DebugLevel: severityDebug,
logrus.InfoLevel: severityInfo,
logrus.WarnLevel: severityWarning,
logrus.ErrorLevel: severityError,
logrus.FatalLevel: severityCritical,
logrus.PanicLevel: severityAlert,
}
// ServiceContext provides the data about the service we are sending to Google.
type ServiceContext struct {
Service string `json:"service,omitempty"`
Version string `json:"version,omitempty"`
}
// ReportLocation is the information about where an error occurred.
type ReportLocation struct {
FilePath string `json:"file,omitempty"`
LineNumber int `json:"line,omitempty"`
FunctionName string `json:"function,omitempty"`
}
// Context is sent with every message to stackdriver.
type Context struct {
Data map[string]interface{} `json:"data,omitempty"`
ReportLocation *ReportLocation `json:"reportLocation,omitempty"`
HTTPRequest *HTTPRequest `json:"httpRequest,omitempty"`
}
// HTTPRequest defines details of a request and response to append to a log.
type HTTPRequest struct {
RequestMethod string `json:"requestMethod,omitempty"`
RequestURL string `json:"requestUrl,omitempty"`
RequestSize string `json:"requestSize,omitempty"`
Status string `json:"status,omitempty"`
ResponseSize string `json:"responseSize,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
RemoteIP string `json:"remoteIp,omitempty"`
ServerIP string `json:"serverIp,omitempty"`
Referer string `json:"referer,omitempty"`
Latency string `json:"latency,omitempty"`
CacheLookup bool `json:"cacheLookup,omitempty"`
CacheHit bool `json:"cacheHit,omitempty"`
CacheValidatedWithOriginServer bool `json:"cacheValidatedWithOriginServer,omitempty"`
CacheFillBytes string `json:"cacheFillBytes,omitempty"`
Protocol string `json:"protocol,omitempty"`
}
// Entry stores a log entry.
type Entry struct {
LogName string `json:"logName,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
Severity severity `json:"severity,omitempty"`
HTTPRequest *HTTPRequest `json:"httpRequest,omitempty"`
Trace string `json:"trace,omitempty"`
ServiceContext *ServiceContext `json:"serviceContext,omitempty"`
Message string `json:"message,omitempty"`
Context *Context `json:"context,omitempty"`
SourceLocation *ReportLocation `json:"sourceLocation,omitempty"`
}
// Formatter implements Stackdriver formatting for logrus.
type Formatter struct {
Service string
Version string
ProjectID string
StackSkip []string
}
// Option lets you configure the Formatter.
type Option func(*Formatter)
// WithService lets you configure the service name used for error reporting.
func WithService(n string) Option {
return func(f *Formatter) {
f.Service = n
}
}
// WithVersion lets you configure the service version used for error reporting.
func WithVersion(v string) Option {
return func(f *Formatter) {
f.Version = v
}
}
// WithProjectID makes sure all entries have your Project information.
func WithProjectID(i string) Option {
return func(f *Formatter) {
f.ProjectID = i
}
}
// WithStackSkip lets you configure which packages should be skipped for locating the error.
func WithStackSkip(v string) Option {
return func(f *Formatter) {
f.StackSkip = append(f.StackSkip, v)
}
}
// NewFormatter returns a new Formatter.
func NewFormatter(options ...Option) *Formatter {
fmtr := Formatter{
StackSkip: []string{
"github.com/sirupsen/logrus",
"github.com/yenta20/logrus-stackdriver-formatter",
},
}
for _, option := range options {
option(&fmtr)
}
return &fmtr
}
func (f *Formatter) errorOrigin() (stack.Call, error) {
skip := func(pkg string) bool {
for _, skip := range f.StackSkip {
if pkg == skip {
return true
}
}
return false
}
// We start at 2 to skip this call and our caller's call.
for i := 2; ; i++ {
c := stack.Caller(i)
// ErrNoFunc indicates we're over traversing the stack.
if _, err := c.MarshalText(); err != nil {
return stack.Call{}, nil
}
pkg := fmt.Sprintf("%+k", c)
// Remove vendoring from package path.
parts := strings.SplitN(pkg, "/vendor/", 2)
pkg = parts[len(parts)-1]
if !skip(pkg) {
return c, nil
}
}
}
// taken from https://github.com/sirupsen/logrus/blob/master/json_formatter.go#L51
func replaceErrors(source logrus.Fields) logrus.Fields {
data := make(logrus.Fields, len(source))
for k, v := range source {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
return data
}
// ToEntry formats a logrus entry to a stackdriver entry.
func (f *Formatter) ToEntry(e *logrus.Entry) (Entry, error) {
severity := levelsToSeverity[e.Level]
ee := Entry{
Message: e.Message,
Severity: severity,
Context: &Context{
Data: replaceErrors(e.Data),
},
}
if val, ok := e.Data["trace"]; ok {
ee.Trace = val.(string)
}
if val, exists := e.Data["httpRequest"]; exists {
r, ok := val.(*HTTPRequest)
if ok {
ee.HTTPRequest = r
}
}
if val, ok := e.Data["logID"]; ok {
ee.LogName = "projects/" + f.ProjectID + "/logs/" + val.(string)
}
if !skipTimestamp {
ee.Timestamp = time.Now().UTC().Format(time.RFC3339Nano)
}
switch severity {
case severityError, severityCritical, severityAlert:
ee.ServiceContext = &ServiceContext{
Service: f.Service,
Version: f.Version,
}
// When using WithError(), the error is sent separately, but Error
// Reporting expects it to be a part of the message so we append it
// instead.
if err, ok := ee.Context.Data["error"]; ok {
ee.Message = fmt.Sprintf("%s: %s", e.Message, err)
delete(ee.Context.Data, "error")
} else {
ee.Message = e.Message
}
// As a convenience, when using supplying the httpRequest field, it
// gets special care.
if reqData, ok := ee.Context.Data["httpRequest"]; ok {
if req, ok := reqData.(*HTTPRequest); ok {
ee.Context.HTTPRequest = req
delete(ee.Context.Data, "httpRequest")
}
}
// Extract report location from call stack.
if c, err := f.errorOrigin(); err == nil {
lineNumber, _ := strconv.ParseInt(fmt.Sprintf("%d", c), 10, 64)
ee.Context.ReportLocation = &ReportLocation{
FilePath: fmt.Sprintf("%+s", c),
LineNumber: int(lineNumber),
FunctionName: fmt.Sprintf("%n", c),
}
ee.SourceLocation = &ReportLocation{
FilePath: fmt.Sprintf("%+s", c),
LineNumber: int(lineNumber),
FunctionName: fmt.Sprintf("%n", c),
}
}
}
return ee, nil
}
// Format formats a logrus entry according to the Stackdriver specifications.
func (f *Formatter) Format(e *logrus.Entry) ([]byte, error) {
ee, _ := f.ToEntry(e)
b, err := json.Marshal(ee)
if err != nil {
return nil, err
}
return append(b, '\n'), nil
}