-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
87 lines (79 loc) · 2.24 KB
/
log.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package utils
import (
"context"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"k8s.io/klog/v2"
"runtime"
"strings"
"unsafe"
)
// These constants identify the log levels in order of increasing severity.
// A message written to a high-severity log file is also written to each
// lower-severity log file.
const (
InfoLog = "INFO"
ErrorLog = "ERROR"
WarningLog = "WARNING"
)
func recordLog(ctx context.Context, prevDepth int, severity string, message string) {
if span := trace.SpanFromContext(ctx); span.IsRecording() {
funcName := "???"
pc, file, line, ok := runtime.Caller(prevDepth + 2)
if !ok {
file = "???"
line = 1
}
if slash := strings.LastIndex(file, "/"); slash >= 0 {
file = file[slash+1:]
}
if f := runtime.FuncForPC(pc); f != nil {
funcName = f.Name()
if slash := strings.LastIndex(funcName, "/"); slash >= 0 {
funcName = funcName[slash+1:]
}
}
eventAttributes := []attribute.KeyValue{
attribute.String("log.severity", severity),
attribute.String("log.message", message),
attribute.String("code.function", funcName),
attribute.String("code.filepath", file),
attribute.Int("code.lineno", line),
}
if severity == ErrorLog {
stack := make([]byte, 4<<10) // default stack length: 4kb
length := runtime.Stack(stack, false)
eventAttributes = append(eventAttributes, attribute.String("exception.stacktrace", unsafe.String(unsafe.SliceData(stack[:length]), length)))
}
span.AddEvent("log", trace.WithAttributes(eventAttributes...))
}
switch severity {
case "INFO":
klog.InfoDepth(prevDepth+2, message)
case "ERROR":
klog.ErrorDepth(prevDepth+2, message)
case "WARNING":
klog.WarningDepth(prevDepth+2, message)
}
}
func InfoWithCtx(ctx context.Context, message string, prevDepth ...int) {
depth := 0
if len(prevDepth) > 0 {
depth = prevDepth[0]
}
recordLog(ctx, depth, InfoLog, message)
}
func WarningWithCtx(ctx context.Context, message string, prevDepth ...int) {
depth := 0
if len(prevDepth) > 0 {
depth = prevDepth[0]
}
recordLog(ctx, depth, WarningLog, message)
}
func ErrorWithCtx(ctx context.Context, message string, prevDepth ...int) {
depth := 0
if len(prevDepth) > 0 {
depth = prevDepth[0]
}
recordLog(ctx, depth, ErrorLog, message)
}