-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsource_location.go
64 lines (52 loc) · 1.71 KB
/
source_location.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
// 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 (
// SourceLocationKey is the Source code location information associated with the log entry, if any.
//
// sourceLocation field:
// - https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#FIELDS.source_location
// - https://cloud.google.com/logging/docs/structured-logging#special-payload-fields
SourceLocationKey = "logging.googleapis.com/sourceLocation"
)
type sourceLocation struct {
*loggingpb.LogEntrySourceLocation
}
// MarshalLogObject implements zapcore.ObjectMarshaller.MarshalLogObject.
func (l *sourceLocation) MarshalLogObject(enc zapcore.ObjectEncoder) error {
enc.AddString("file", l.GetFile())
enc.AddInt64("line", l.GetLine())
enc.AddString("function", l.GetFunction())
return nil
}
func newSource(pc uintptr, file string, line int, ok bool) *sourceLocation {
if !ok {
return nil
}
var function string
if fn := FuncForPC(pc); fn != nil {
function = strings.TrimPrefix(fn.Name(), filepath.Join(build.Default.GOPATH, "src")+"/")
}
loc := &sourceLocation{
LogEntrySourceLocation: &loggingpb.LogEntrySourceLocation{
File: file,
Line: int64(line),
Function: function,
},
}
return loc
}
// SourceLocation adds the Cloud Logging "sourceLocation" field.
//
// LogEntrySourceLocation: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogEntrySourceLocation
func SourceLocation(pc uintptr, file string, line int, ok bool) zapcore.Field {
return zap.Object(SourceLocationKey, newSource(pc, file, line, ok))
}