log_capture.go RawHistoryFolder
1//go:build webkit_cgo
2
3package webkit
4
5/*
6#include "log_capture.h"
7*/
8import "C"
9
10import (
11 "time"
12 "unsafe"
13
14 "github.com/bnema/dumber/internal/logging"
15)
16
17var webkitCaptureActive = false
18var webkitCaptureChan chan struct{}
19
20//export goWebKitLogHandler
21func goWebKitLogHandler(domain *C.char, level C.int, message *C.char) {
22 goDomain := C.GoString(domain)
23 goMessage := C.GoString(message)
24
25 var levelStr string
26 switch level {
27 case C.G_LOG_LEVEL_ERROR:
28 levelStr = "ERROR"
29 case C.G_LOG_LEVEL_CRITICAL:
30 levelStr = "CRITICAL"
31 case C.G_LOG_LEVEL_WARNING:
32 levelStr = "WARNING"
33 case C.G_LOG_LEVEL_MESSAGE:
34 levelStr = "MESSAGE"
35 case C.G_LOG_LEVEL_INFO:
36 levelStr = "INFO"
37 case C.G_LOG_LEVEL_DEBUG:
38 levelStr = "DEBUG"
39 default:
40 levelStr = "UNKNOWN"
41 }
42
43 logMessage := goMessage
44 if goDomain != "" {
45 logMessage = "[" + goDomain + "] " + goMessage
46 }
47
48 // Send to logging system with appropriate level
49 if logger := logging.GetLogger(); logger != nil {
50 logger.WriteTagged("WEBKIT-"+levelStr, logMessage)
51 }
52}
53
54// InitWebKitLogCapture initializes the WebKit log capture system
55func InitWebKitLogCapture() error {
56 if webkitCaptureActive {
57 return nil
58 }
59
60 // Initialize C-level log capture
61 C.webkit_init_log_capture()
62
63 // Set up GLib log handlers
64 C.webkit_setup_glib_log_handlers()
65
66 // Create channel for stopping capture
67 webkitCaptureChan = make(chan struct{})
68
69 // Start goroutine to read captured C output
70 go webkitLogReader()
71
72 webkitCaptureActive = true
73 return nil
74}
75
76// StopWebKitLogCapture stops the WebKit log capture
77func StopWebKitLogCapture() {
78 if !webkitCaptureActive {
79 return
80 }
81
82 // Signal the reader goroutine to stop
83 close(webkitCaptureChan)
84
85 // Stop C-level capture
86 C.webkit_stop_log_capture()
87
88 webkitCaptureActive = false
89}
90
91// webkitLogReader reads captured C output in a goroutine
92func webkitLogReader() {
93 buffer := make([]byte, 4096)
94
95 for {
96 select {
97 case <-webkitCaptureChan:
98 return
99 default:
100 // Try to read captured output
101 n := int(C.webkit_read_captured_log((*C.char)(unsafe.Pointer(&buffer[0])), C.int(len(buffer))))
102 if n > 0 {
103 message := string(buffer[:n])
104 if logger := logging.GetLogger(); logger != nil {
105 logger.WriteTagged("WEBKIT-PRINTF", message)
106 }
107 }
108
109 // Small delay to prevent busy waiting
110 time.Sleep(10 * time.Millisecond)
111 }
112 }
113}
114
115// StartWebKitOutputCapture starts capturing webkit stdout/stderr
116func StartWebKitOutputCapture() {
117 if webkitCaptureActive {
118 C.webkit_start_log_capture()
119 }
120}
121
122// IsWebKitLogCaptureActive returns whether WebKit log capture is active
123func IsWebKitLogCaptureActive() bool {
124 return webkitCaptureActive
125}