Skip to content

Commit 70c7e96

Browse files
committed
Use slog with proper levels for logging
1 parent 861dc11 commit 70c7e96

File tree

24 files changed

+255
-196
lines changed

24 files changed

+255
-196
lines changed

ebpf/bpfwrapper/deleteProbes.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package bpfwrapper
22

33
import (
4-
"fmt"
4+
"log/slog"
55
"os/exec"
66
"strings"
77
)
@@ -12,7 +12,7 @@ func DeleteExistingAktoKernelProbes() {
1212

1313
listOutput, err := listCmd.Output()
1414
if err != nil {
15-
fmt.Println("Error listing kprobes:", err)
15+
slog.Error("Error listing kprobes", "error", err)
1616
return
1717
}
1818

@@ -37,9 +37,9 @@ func DeleteExistingAktoKernelProbes() {
3737

3838
// Run the command
3939
if err := deleteCmd.Run(); err != nil {
40-
fmt.Printf("Error deleting kprobe %s: %v\n", kprobeName, err)
40+
slog.Error("Error deleting kprobe", "kprobe", kprobeName, "error", err)
4141
} else {
42-
fmt.Printf("Deleted kprobe %s\n", kprobeName)
42+
slog.Debug("Deleted kprobe", "kprobe", kprobeName)
4343
}
4444
}
4545
}

ebpf/bpfwrapper/eventCallbacks.go

Lines changed: 34 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ package bpfwrapper
33
import (
44
"bytes"
55
"encoding/binary"
6-
"log"
6+
"log/slog"
77
"unsafe"
88

99
"github.com/akto-api-security/mirroring-api-logging/ebpf/connections"
@@ -28,11 +28,16 @@ func SocketOpenEventCallback(inputChan chan []byte, connectionFactory *connectio
2828

2929
var event structs.SocketOpenEvent
3030
if err := binary.Read(bytes.NewReader(data), bcc.GetHostByteOrder(), &event); err != nil {
31-
log.Printf("Failed to decode received data on socket open: %+v", err)
31+
slog.Error("Failed to decode received data on socket open", "error", err)
3232
continue
3333
}
3434
connId := event.ConnId
35-
utils.LogIngest("Received open fd: %v id: %v ts: %v ip: %v port: %v\n", connId.Fd, connId.Id, connId.Conn_start_ns, connId.Ip, connId.Port)
35+
slog.Debug("Received socket open event",
36+
"fd", connId.Fd,
37+
"id", connId.Id,
38+
"timestamp", connId.Conn_start_ns,
39+
"ip", connId.Ip,
40+
"port", connId.Port)
3641
connectionFactory.CreateIfNotExists(connId)
3742
connectionFactory.SendEvent(connId, &event)
3843
}
@@ -45,12 +50,17 @@ func SocketCloseEventCallback(inputChan chan []byte, connectionFactory *connecti
4550
}
4651
var event structs.SocketCloseEvent
4752
if err := binary.Read(bytes.NewReader(data), bcc.GetHostByteOrder(), &event); err != nil {
48-
log.Printf("Failed to decode received data on socket close: %+v", err)
53+
slog.Error("Failed to decode received data on socket close", "error", err)
4954
continue
5055
}
5156

5257
connId := event.ConnId
53-
utils.LogIngest("Received close on: fd: %v id: %v ts: %v ip: %v port: %v\n", connId.Fd, connId.Id, connId.Conn_start_ns, connId.Ip, connId.Port)
58+
slog.Debug("Received close on",
59+
"fd", connId.Fd,
60+
"id", connId.Id,
61+
"timestamp", connId.Conn_start_ns,
62+
"ip", connId.Ip,
63+
"port", connId.Port)
5464
connectionFactory.SendEvent(connId, &event)
5565
}
5666
}
@@ -90,7 +100,7 @@ func SocketDataEventCallback(inputChan chan []byte, connectionFactory *connectio
90100
}
91101

92102
if !(connectionFactory.CanBeFilled() && connections.BufferCheck()) {
93-
utils.LogIngest("Connections filled")
103+
slog.Debug("Connections filled")
94104
continue
95105
}
96106

@@ -100,10 +110,10 @@ func SocketDataEventCallback(inputChan chan []byte, connectionFactory *connectio
100110
// Since the Msg field might be mostly empty, binary.read fails.
101111
// So we split the loading into the fixed size attribute parts, and copying the message separately.
102112

103-
// fmt.Printf("data: %v\n", data)
113+
// slog.Debug("data", "data", data)
104114

105115
if err := binary.Read(bytes.NewReader(data[:eventAttributesSize]), bcc.GetHostByteOrder(), &event.Attr); err != nil {
106-
utils.LogIngest("Failed to decode received data: %+v", err)
116+
slog.Error("Failed to decode received data", "error", err)
107117
continue
108118
}
109119

@@ -120,7 +130,12 @@ func SocketDataEventCallback(inputChan chan []byte, connectionFactory *connectio
120130

121131
_, ok := ignorePortsMap[connId.Port]
122132
if ignorePorts && ok {
123-
utils.LogIngest("Ignoring data for ignore port fd: %v id: %v ts: %v rc: %v wc: %v\n", connId.Fd, connId.Id, connId.Conn_start_ns, event.Attr.ReadEventsCount, event.Attr.WriteEventsCount)
133+
slog.Debug("Ignoring data for ignore port",
134+
"fd", connId.Fd,
135+
"id", connId.Id,
136+
"timestamp", connId.Conn_start_ns,
137+
"rc", event.Attr.ReadEventsCount,
138+
"wc", event.Attr.WriteEventsCount)
124139
continue
125140
}
126141

@@ -134,6 +149,15 @@ func SocketDataEventCallback(inputChan chan []byte, connectionFactory *connectio
134149
connectionFactory.SendEvent(connId, &event)
135150
connections.UpdateBufferSize(uint64(utils.Abs(bytesSent)))
136151

137-
utils.LogIngest("Got data fd: %v id: %v ts: %v ip: %v port: %v data: %v rc: %v wc: %v ssl: %v\n", connId.Fd, connId.Id, connId.Conn_start_ns, connId.Ip, connId.Port, dataStr, event.Attr.ReadEventsCount, event.Attr.WriteEventsCount, event.Attr.Ssl)
152+
slog.Debug("Got data",
153+
"fd", connId.Fd,
154+
"id", connId.Id,
155+
"timestamp", connId.Conn_start_ns,
156+
"ip", connId.Ip,
157+
"port", connId.Port,
158+
"data", dataStr,
159+
"rc", event.Attr.ReadEventsCount,
160+
"wc", event.Attr.WriteEventsCount,
161+
"ssl", event.Attr.Ssl)
138162
}
139163
}

ebpf/bpfwrapper/kprobes.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package bpfwrapper
22

33
import (
4-
"log"
4+
"log/slog"
55
"runtime"
66

77
"github.com/iovisor/gobpf/bcc"
@@ -78,25 +78,25 @@ func AttachKprobes(bpfModule *bcc.Module, kprobeList []Kprobe) error {
7878

7979
probeFD, err := bpfModule.LoadKprobe(probe.HookName)
8080
if err != nil {
81-
log.Printf("failed to load %q due to: %v, skipping", probe.HookName, err)
81+
slog.Error("failed to load kprobe", "hook", probe.HookName, "error", err)
8282
continue
8383
}
8484

8585
switch probe.Type {
8686
case EntryType:
87-
log.Printf("Loading %q for %q as kprobe\n", probe.HookName, functionToHook)
87+
slog.Debug("Loading kprobe", "hook", probe.HookName, "as kprobe", functionToHook)
8888
if err = bpfModule.AttachKprobe(functionToHook, probeFD, maxActiveConnections); err != nil {
89-
log.Printf("failed to attach kprobe %q to %q due to: %v, skipping", probe.HookName, functionToHook, err)
89+
slog.Error("failed to attach kprobe", "hook", probe.HookName, "function", functionToHook, "error", err)
9090
}
9191
continue
9292
case ReturnType:
93-
log.Printf("Loading %q for %q as kretprobe\n", probe.HookName, functionToHook)
93+
slog.Debug("Loading kretprobe", "hook", probe.HookName, "as kretprobe", functionToHook)
9494
if err = bpfModule.AttachKretprobe(functionToHook, probeFD, maxActiveConnections); err != nil {
95-
log.Printf("failed to attach kretprobe %q to %q due to: %v, skipping", probe.HookName, functionToHook, err)
95+
slog.Error("failed to attach kretprobe", "hook", probe.HookName, "function", functionToHook, "error", err)
9696
}
9797
continue
9898
default:
99-
log.Printf("unknown Kprobe type %d given for %q, skipping", probe.Type, probe.HookName)
99+
slog.Error("unknown Kprobe type given for hook", "type", probe.Type, "hook", probe.HookName)
100100
continue
101101
}
102102
}

ebpf/bpfwrapper/uprobes.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ package bpfwrapper
22

33
import (
44
"fmt"
5-
"log"
5+
"log/slog"
66
"regexp"
77
"strings"
88

@@ -36,46 +36,46 @@ func AttachUprobes(soPath string, pid int, bpfModule *bcc.Module, uprobeList []U
3636

3737
switch probe.Type {
3838
case EntryType:
39-
log.Printf("Loading %q for %q as uprobe\n", probe.HookName, probe.FunctionToHook)
39+
slog.Debug("Loading uprobe", "hook", probe.HookName, "as uprobe", functionToHook)
4040
if err = bpfModule.AttachUprobe(soPath, functionToHook, probeFD, pid); err != nil {
4141
return fmt.Errorf("failed to attach uprobe %q to %q due to: %v", probe.HookName, functionToHook, err)
4242
}
4343
case ReturnType:
44-
log.Printf("Loading %q for %q as uretprobe\n", probe.HookName, probe.FunctionToHook)
44+
slog.Debug("Loading uretprobe", "hook", probe.HookName, "as uretprobe", functionToHook)
4545
if err = bpfModule.AttachUretprobe(soPath, functionToHook, probeFD, pid); err != nil {
4646
return fmt.Errorf("failed to attach uretprobe %q to %q due to: %v", probe.HookName, functionToHook, err)
4747
}
4848
case EntryType_Matching_Suf:
49-
log.Printf("Loading %q for %q as matching uprobe\n", probe.HookName, probe.FunctionToHook)
49+
slog.Debug("Loading matching uprobe", "hook", probe.HookName, "as matching uprobe", functionToHook)
5050
regex := getSuffixRegex(functionToHook)
5151

5252
if err = bpfModule.AttachMatchingUprobes(soPath, regex, probeFD, pid); err != nil {
5353
return fmt.Errorf("failed to attach matching uprobe %q to %q due to: %v", probe.HookName, functionToHook, err)
5454
}
5555
case ReturnType_Matching_Suf_Addr:
5656
for _, add := range probe.Addresses {
57-
log.Printf("Loading %q for %q as matching uretprobe with add %v\n", probe.HookName, probe.FunctionToHook, add)
57+
slog.Debug("Loading matching uretprobe", "hook", probe.HookName, "as matching uretprobe", functionToHook, "with add", add)
5858
path, addr, err := bcc.ResolveSymbolPath(soPath, functionToHook, 0x0, pid)
5959
if err != nil {
60-
fmt.Printf("resolv error: %v\n", err)
60+
slog.Error("resolv error", "error", err)
6161
continue
6262
}
6363
finalAddr := addr + add
6464
evName := fmt.Sprintf("akto_p_%s_0x%x", uprobeRegexp.ReplaceAllString(path, "_"), finalAddr)
6565
if err = bpfModule.AttachUProbeInternal(evName, bcc.BPF_PROBE_ENTRY, path, finalAddr, probeFD, pid); err != nil {
66-
fmt.Printf("failed to attach matching uretprobe %q to %q due to: %v\n", probe.HookName, functionToHook, err)
66+
slog.Error("failed to attach matching uretprobe", "hook", probe.HookName, "as matching uretprobe", functionToHook, "error", err)
6767
continue
6868
}
6969
}
7070
case EntryType_Matching_Pre:
71-
log.Printf("Loading %q for %q as pre matching uprobe\n", probe.HookName, probe.FunctionToHook)
71+
slog.Debug("Loading matching uprobe", "hook", probe.HookName, "as matching uprobe", functionToHook)
7272
regex := getPrefixRegex(functionToHook)
7373

7474
if err = bpfModule.AttachMatchingUprobes(soPath, regex, probeFD, pid); err != nil {
7575
return fmt.Errorf("failed to attach pre matching uprobe %q to %q due to: %v", probe.HookName, functionToHook, err)
7676
}
7777
case ReturnType_Matching_Pre:
78-
log.Printf("Loading %q for %q as matching uprobe\n", probe.HookName, probe.FunctionToHook)
78+
slog.Debug("Loading matching uretprobe", "hook", probe.HookName, "as matching uretprobe", functionToHook)
7979
regex := getPrefixRegex(functionToHook)
8080

8181
if err = bpfModule.AttachMatchingUretprobes(soPath, regex, probeFD, pid); err != nil {

ebpf/connections/factory.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ package connections
33
import (
44
"encoding/binary"
55
"fmt"
6-
"log"
6+
"log/slog"
77
"net"
88
"sort"
99

@@ -162,7 +162,7 @@ func UpdateBufferSize(bufferSize uint64) {
162162
currentTotalBuffer += int64(bufferSize)
163163
if currentTotalBuffer/(1024*1024) > lastPrint {
164164
lastPrint = currentTotalBuffer / (1024 * 1024)
165-
log.Printf("Current total buffer: %v %v\n", currentTotalBuffer, lastPrint)
165+
slog.Debug("Current total buffer", "buffer", currentTotalBuffer, "lastPrint", lastPrint)
166166
}
167167
}
168168
}
@@ -249,12 +249,12 @@ func (factory *Factory) DeleteWorker(connectionID structs.ConnID) {
249249
if (time.Now().UnixMilli())-lastMemCheck > int64(memCheckInterval) {
250250
lastMemCheck = time.Now().UnixMilli()
251251
mem := utils.LogMemoryStats()
252-
log.Printf("Requests processed : %v %v\n", requestProcessCount, lastMemCheck)
253-
log.Printf("connection factory size : %v %v %v\n", len(factory.connections), len(factory.processor), lastMemCheck)
252+
slog.Debug("Requests processed", "count", requestProcessCount, "lastMemCheck", lastMemCheck)
253+
slog.Debug("connection factory size", "connections", len(factory.connections), "processors", len(factory.processor), "lastMemCheck", lastMemCheck)
254254
requestProcessCount = 0
255255
if mem >= bufferMemThreshold {
256256
trackersToDelete := make(map[structs.ConnID]struct{})
257-
metaUtils.LogProcessing("Deleting all trackers at mem: %v \n", mem)
257+
slog.Debug("Deleting all trackers at mem", "mem", mem)
258258
for k := range factory.connections {
259259
trackersToDelete[k] = struct{}{}
260260
}

ebpf/main.go

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@ package main
22

33
import (
44
"fmt"
5+
"log/slog"
56
"os"
67
"os/signal"
78
"runtime"
89
"runtime/pprof"
910
"strconv"
1011
"sync"
1112

12-
"log"
1313
"strings"
1414
"syscall"
1515
"time"
@@ -59,7 +59,7 @@ func replaceArchType() {
5959

6060
func isArmArch() bool {
6161
arch := runtime.GOARCH
62-
fmt.Printf("arch type detected: %v\n", arch)
62+
slog.Debug("arch type detected", "arch", arch)
6363
if strings.Contains(arch, "arm") {
6464
return true
6565
}
@@ -68,7 +68,7 @@ func isArmArch() bool {
6868

6969
func isAmdArch() bool {
7070
arch := runtime.GOARCH
71-
fmt.Printf("arch type detected: %v\n", arch)
71+
slog.Debug("arch type detected", "arch", arch)
7272
if strings.Contains(arch, "amd") {
7373
return true
7474
}
@@ -86,7 +86,8 @@ func run() {
8686

8787
byteString, err := os.ReadFile("./kernel/module.cc")
8888
if err != nil {
89-
log.Panic(err)
89+
slog.Error("failed to read kernel module", "error", err)
90+
panic(err)
9091
}
9192
source = string(byteString)
9293

@@ -98,7 +99,8 @@ func run() {
9899

99100
bpfModule := bcc.NewModule(source, []string{})
100101
if bpfModule == nil {
101-
log.Panic("bpf is nil")
102+
slog.Error("failed to create BPF module", "error", "module is nil")
103+
panic("bpf module is nil")
102104
}
103105
defer bpfModule.Close()
104106

@@ -140,7 +142,8 @@ func run() {
140142
hooks = append(hooks, bpfwrapper.Level4hooks...)
141143

142144
if err := bpfwrapper.LaunchPerfBufferConsumers(bpfModule, connectionFactory, callbacks); err != nil {
143-
log.Panic(err)
145+
slog.Error("failed to launch perf buffer consumers", "error", err)
146+
panic(err)
144147
}
145148

146149
if err := bpfwrapper.AttachKprobes(bpfModule, hooks); err != nil {
@@ -160,11 +163,11 @@ func run() {
160163

161164
if captureSsl == "true" || captureAll == "true" {
162165
go func() {
163-
fmt.Printf("Starting to attach to processes in ticker start\n")
166+
slog.Debug("Starting to attach to processes in ticker start")
164167
ticker := time.NewTicker(pollInterval) // Create a ticker to trigger every minute
165168
defer ticker.Stop()
166169
for range ticker.C {
167-
fmt.Printf("Starting to attach to processes in ticker\n")
170+
slog.Debug("Starting to attach to processes in ticker")
168171
if !isRunning_2 {
169172
mu_2.Lock()
170173
if isRunning_2 {
@@ -174,16 +177,16 @@ func run() {
174177
isRunning_2 = true
175178
mu_2.Unlock()
176179

177-
fmt.Printf("Starting to attach to processes\n")
180+
slog.Debug("Starting to attach to processes")
178181
processFactory.AddNewProcessesToProbe(bpfModule)
179-
fmt.Printf("Ended attaching to processes\n")
182+
slog.Debug("Ended attaching to processes")
180183
mu_2.Lock()
181184
isRunning_2 = false
182185
mu_2.Unlock()
183186
}
184-
fmt.Printf("Ended attaching to processes in ticker\n")
187+
slog.Debug("Ended attaching to processes in ticker")
185188
}
186-
fmt.Printf("Ended attaching to processes in ticker end\n")
189+
slog.Debug("Ended attaching to processes in ticker end")
187190
}()
188191
}
189192

@@ -208,9 +211,9 @@ func run() {
208211

209212
sig := make(chan os.Signal, 1)
210213
signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
211-
log.Println("Sniffer is ready")
214+
slog.Debug("sniffer is ready")
212215
<-sig
213-
log.Println("Signaled to terminate")
216+
slog.Debug("signaled to terminate")
214217
}
215218

216219
func captureMemoryProfile() {
@@ -232,11 +235,11 @@ func captureCpuProfile() {
232235
if err := pprof.StartCPUProfile(f); err != nil {
233236
panic("could not start CPU profile: " + err.Error())
234237
}
235-
fmt.Println("CPU profiling started")
238+
slog.Debug("CPU profiling started")
236239

237240
// Allow profiling for a certain duration or simulate workload
238241
time.Sleep(12 * time.Second) // Sleep for 10 seconds to simulate CPU activity
239242

240243
pprof.StopCPUProfile()
241-
fmt.Println("CPU profiling stopped")
244+
slog.Debug("CPU profiling stopped")
242245
}

0 commit comments

Comments
 (0)