From 757cf83b7eac648f964cf02b1eca12a70f4088c0 Mon Sep 17 00:00:00 2001 From: Etienne Perot Date: Tue, 2 Jan 2024 18:39:36 -0800 Subject: [PATCH] Add call site information to JSON-formatted logs. PiperOrigin-RevId: 595258070 --- pkg/log/json.go | 13 +++++++++++-- pkg/log/json_k8s.go | 13 +++++++++++-- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/pkg/log/json.go b/pkg/log/json.go index a7f55a9f9..a57bc101f 100644 --- a/pkg/log/json.go +++ b/pkg/log/json.go @@ -17,6 +17,8 @@ package log import ( "encoding/json" "fmt" + "runtime" + "strings" "time" ) @@ -62,9 +64,16 @@ type JSONEmitter struct { } // Emit implements Emitter.Emit. -func (e JSONEmitter) Emit(_ int, level Level, timestamp time.Time, format string, v ...any) { +func (e JSONEmitter) Emit(depth int, level Level, timestamp time.Time, format string, v ...any) { + logLine := fmt.Sprintf(format, v...) + if _, file, line, ok := runtime.Caller(depth + 1); ok { + if slash := strings.LastIndexByte(file, byte('/')); slash >= 0 { + file = file[slash+1:] // Trim any directory path from the file. + } + logLine = fmt.Sprintf("%s:%d] %s", file, line, logLine) + } j := jsonLog{ - Msg: fmt.Sprintf(format, v...), + Msg: logLine, Level: level, Time: timestamp, } diff --git a/pkg/log/json_k8s.go b/pkg/log/json_k8s.go index 0105c0682..8f5aab5a9 100644 --- a/pkg/log/json_k8s.go +++ b/pkg/log/json_k8s.go @@ -17,6 +17,8 @@ package log import ( "encoding/json" "fmt" + "runtime" + "strings" "time" ) @@ -33,9 +35,16 @@ type K8sJSONEmitter struct { } // Emit implements Emitter.Emit. -func (e K8sJSONEmitter) Emit(_ int, level Level, timestamp time.Time, format string, v ...any) { +func (e K8sJSONEmitter) Emit(depth int, level Level, timestamp time.Time, format string, v ...any) { + logLine := fmt.Sprintf(format, v...) + if _, file, line, ok := runtime.Caller(depth + 1); ok { + if slash := strings.LastIndexByte(file, byte('/')); slash >= 0 { + file = file[slash+1:] // Trim any directory path from the file. + } + logLine = fmt.Sprintf("%s:%d] %s", file, line, logLine) + } j := k8sJSONLog{ - Log: fmt.Sprintf(format, v...), + Log: logLine, Level: level, Time: timestamp, }