Skip to content

Commit 19c2578

Browse files
committed
Make sure the type assertions do not panic but are logged.
1 parent daf542d commit 19c2578

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

ngcplogger.go

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@ import (
55
"encoding/json"
66
"errors"
77
"fmt"
8+
"log/slog"
89
"net/http"
910
"net/url"
11+
"reflect"
12+
"runtime"
1013
"sync"
1114
"sync/atomic"
1215
"time"
@@ -362,34 +365,48 @@ func (l *nGCPLogger) extractMsgFromPayload(m map[string]any) {
362365
}
363366
}
364367

368+
func assertOrLog[T any](val any) T {
369+
var v T
370+
var ok bool
371+
v, ok = val.(T)
372+
if !ok {
373+
_, file, line, ok := runtime.Caller(1)
374+
if !ok {
375+
file = "unknown"
376+
}
377+
slog.Error("unexpected type", "want", reflect.TypeOf(v).String(), "got", reflect.TypeOf(val).String(), "file", file, "line", line)
378+
}
379+
return v
380+
}
381+
365382
func (l *nGCPLogger) extractGcpFromPayload(m map[string]any, entry *logging.Entry) {
366383

367384
if l.extractGcp {
368385
if val, exists := m["logging.googleapis.com/sourceLocation"]; exists {
369-
v := val.(map[string]any)
386+
v := assertOrLog[map[string]any](val)
370387
entry.SourceLocation = &loggingpb.LogEntrySourceLocation{
371-
File: v["file"].(string),
372-
Line: int64(v["line"].(float64)),
373-
Function: v["function"].(string),
388+
File: assertOrLog[string](v["file"]),
389+
Line: int64(assertOrLog[float64](v["line"])),
390+
Function: assertOrLog[string](v["function"]),
374391
}
375392
delete(m, "logging.googleapis.com/sourceLocation")
376393
}
377394
if val, exists := m["logging.googleapis.com/trace"]; exists {
378-
entry.Trace = val.(string)
395+
entry.Trace = assertOrLog[string](val)
379396
delete(m, "logging.googleapis.com/trace")
380397
}
381398
if val, exists := m["logging.googleapis.com/spanId"]; exists {
382-
entry.SpanID = val.(string)
399+
entry.SpanID = assertOrLog[string](val)
383400
delete(m, "logging.googleapis.com/spanId")
384401
}
385402
if val, exists := m["logging.googleapis.com/trace_sampled"]; exists {
386-
entry.TraceSampled = val.(bool)
403+
entry.TraceSampled = assertOrLog[bool](val)
387404
delete(m, "logging.googleapis.com/trace_sampled")
388405
}
389406
if val, exists := m["logging.googleapis.com/labels"]; exists {
390-
v := val.(map[string]any)
407+
v := assertOrLog[map[string]any](val)
391408
for k, v := range v {
392-
entry.Labels[k] = v.(string)
409+
entry.Labels[k] = assertOrLog[string](v)
393410
}
394411
delete(m, "logging.googleapis.com/labels")
395412
}

0 commit comments

Comments
 (0)