github.com/zchee/zap-cloudlogging@v0.0.0-20220819025602-19b026d3900e/error_report.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 contextKey = "context" 18 ) 19 20 // reportLocation is the source code location information associated with the log entry 21 // for the purpose of reporting an error, if any. 22 type reportLocation struct { 23 *logpb.LogEntrySourceLocation 24 } 25 26 // MarshalLogObject implements zapcore.ObjectMarshaller.MarshalLogObject. 27 func (l reportLocation) MarshalLogObject(enc zapcore.ObjectEncoder) error { 28 enc.AddString("filePath", l.GetFile()) 29 enc.AddInt64("lineNumber", l.GetLine()) 30 enc.AddString("functionName", l.GetFunction()) 31 32 return nil 33 } 34 35 // reportContext is the context information attached to a log for reporting errors. 36 type reportContext struct { 37 ReportLocation *reportLocation `json:"reportLocation"` 38 } 39 40 // MarshalLogObject implements zapcore.ObjectMarshaller.MarshalLogObject. 41 func (c reportContext) MarshalLogObject(enc zapcore.ObjectEncoder) error { 42 return enc.AddObject("reportLocation", c.ReportLocation) 43 } 44 45 func newReportContext(pc uintptr, file string, line int, ok bool) *reportContext { 46 if !ok { 47 return nil 48 } 49 50 var function string 51 if fn := FuncForPC(pc); fn != nil { 52 function = strings.TrimPrefix(fn.Name(), filepath.Join(build.Default.GOPATH, "src")+"/") 53 } 54 ctx := &reportContext{ 55 ReportLocation: &reportLocation{ 56 LogEntrySourceLocation: &logpb.LogEntrySourceLocation{ 57 File: file, 58 Line: int64(line), 59 Function: function, 60 }, 61 }, 62 } 63 64 return ctx 65 } 66 67 // ErrorReport adds the Cloud Logging "context" field for getting the log line reported as error. 68 // 69 // https://cloud.google.com/error-reporting/docs/formatting-error-messages 70 func ErrorReport(pc uintptr, file string, line int, ok bool) zap.Field { 71 return zap.Object(contextKey, newReportContext(pc, file, line, ok)) 72 }