Add call site information to JSON-formatted logs.

PiperOrigin-RevId: 595258070
This commit is contained in:
Etienne Perot
2024-01-02 18:43:05 -08:00
committed by gVisor bot
parent e6a42ae594
commit 757cf83b7e
2 changed files with 22 additions and 4 deletions
+11 -2
View File
@@ -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,
}
+11 -2
View File
@@ -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,
}