-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patherror_report.go
72 lines (59 loc) · 1.91 KB
/
error_report.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
// Copyright 2022 The zapcl Authors
// SPDX-License-Identifier: BSD-3-Clause
package zapcl
import (
"go/build"
"path/filepath"
"strings"
"cloud.google.com/go/logging/apiv2/loggingpb"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const (
contextKey = "context"
)
// reportLocation is the source code location information associated with the log entry
// for the purpose of reporting an error, if any.
type reportLocation struct {
*loggingpb.LogEntrySourceLocation
}
// MarshalLogObject implements zapcore.ObjectMarshaller.MarshalLogObject.
func (l reportLocation) MarshalLogObject(enc zapcore.ObjectEncoder) error {
enc.AddString("filePath", l.GetFile())
enc.AddInt64("lineNumber", l.GetLine())
enc.AddString("functionName", l.GetFunction())
return nil
}
// reportContext is the context information attached to a log for reporting errors.
type reportContext struct {
ReportLocation *reportLocation `json:"reportLocation"`
}
// MarshalLogObject implements zapcore.ObjectMarshaller.MarshalLogObject.
func (c reportContext) MarshalLogObject(enc zapcore.ObjectEncoder) error {
return enc.AddObject("reportLocation", c.ReportLocation)
}
func newReportContext(pc uintptr, file string, line int, ok bool) *reportContext {
if !ok {
return nil
}
var function string
if fn := FuncForPC(pc); fn != nil {
function = strings.TrimPrefix(fn.Name(), filepath.Join(build.Default.GOPATH, "src")+"/")
}
ctx := &reportContext{
ReportLocation: &reportLocation{
LogEntrySourceLocation: &loggingpb.LogEntrySourceLocation{
File: file,
Line: int64(line),
Function: function,
},
},
}
return ctx
}
// ErrorReport adds the Cloud Logging "context" field for getting the log line reported as error.
//
// https://cloud.google.com/error-reporting/docs/formatting-error-messages
func ErrorReport(pc uintptr, file string, line int, ok bool) zap.Field {
return zap.Object(contextKey, newReportContext(pc, file, line, ok))
}