github.com/zchee/zap-cloudlogging@v0.0.0-20220819025602-19b026d3900e/source_location.go (about) 1 // Copyright 2022 The zap-cloudlogging Authors 2 // SPDX-License-Identifier: BSD-3-Clause 3 4 package zapcloudlogging 5 6 import ( 7 "go/build" 8 "path/filepath" 9 "strings" 10 11 "go.uber.org/zap" 12 "go.uber.org/zap/zapcore" 13 logpb "google.golang.org/genproto/googleapis/logging/v2" 14 ) 15 16 const ( 17 // SourceLocationKey is the Source code location information associated with the log entry, if any. 18 // 19 // sourceLocation field: 20 // - https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#FIELDS.source_location 21 // - https://cloud.google.com/logging/docs/structured-logging#special-payload-fields 22 SourceLocationKey = "logging.googleapis.com/sourceLocation" 23 ) 24 25 type sourceLocation struct { 26 *logpb.LogEntrySourceLocation 27 } 28 29 // MarshalLogObject implements zapcore.ObjectMarshaller.MarshalLogObject. 30 func (l sourceLocation) MarshalLogObject(enc zapcore.ObjectEncoder) error { 31 enc.AddString("file", l.GetFile()) 32 enc.AddInt64("line", l.GetLine()) 33 enc.AddString("function", l.GetFunction()) 34 35 return nil 36 } 37 38 func newSource(pc uintptr, file string, line int, ok bool) *sourceLocation { 39 if !ok { 40 return nil 41 } 42 43 var function string 44 if fn := FuncForPC(pc); fn != nil { 45 function = strings.TrimPrefix(fn.Name(), filepath.Join(build.Default.GOPATH, "src")+"/") 46 } 47 48 loc := &sourceLocation{ 49 LogEntrySourceLocation: &logpb.LogEntrySourceLocation{ 50 File: file, 51 Line: int64(line), 52 Function: function, 53 }, 54 } 55 56 return loc 57 } 58 59 // SourceLocation adds the Cloud Logging "sourceLocation" field. 60 // 61 // LogEntrySourceLocation: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogEntrySourceLocation 62 func SourceLocation(pc uintptr, file string, line int, ok bool) zapcore.Field { 63 return zap.Object(SourceLocationKey, newSource(pc, file, line, ok)) 64 }