@echoteam/signoz-react 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,6 +24,12 @@ Library React untuk monitoring dan tracing aplikasi menggunakan OpenTelemetry da
24
24
  - First Paint, First Contentful Paint
25
25
  - DOM Content Loaded, Load Complete
26
26
  - Resource timing
27
+ - **WebSocket Logging**: Otomatis track WebSocket connections dan messages
28
+ - Track connection open, close, error
29
+ - Log messages sent dan received
30
+ - Extract message type dan text dari JSON
31
+ - Connection duration tracking
32
+ - Data tersimpan di SignOz span attributes
27
33
  - **No Click Tracking**: User interaction (click events) tidak di-track untuk privacy dan performa
28
34
  - **Error Boundary**: Komponen React untuk menangkap dan melaporkan error dengan tracing
29
35
  - **Error Page**: Halaman error untuk React Router dengan integrasi tracing
@@ -71,6 +77,10 @@ REACT_APP_SIGNOZ_ENABLE_DOCUMENT_LOAD=false # default: false
71
77
  REACT_APP_SIGNOZ_ENABLE_ERROR_TRACKING=true # default: true
72
78
  REACT_APP_SIGNOZ_ENABLE_NAVIGATION_TRACKING=false # default: false
73
79
 
80
+ # WebSocket Logging (opsional, default: false)
81
+ REACT_APP_SIGNOZ_ENABLE_WEBSOCKET_LOGGING=false
82
+ REACT_APP_SIGNOZ_LOG_WEBSOCKET_MESSAGES=false
83
+
74
84
  # Console Logging (opsional, default: false)
75
85
  REACT_APP_SIGNOZ_ENABLE_CONSOLE_LOG=false
76
86
  ```
@@ -137,6 +147,9 @@ initializeSignOzTracing({
137
147
  enableDocumentLoad: false, // Track page load performance (default: false)
138
148
  enableErrorTracking: true, // Track unhandled errors (default: true)
139
149
  enableNavigationTracking: false, // Track route changes (default: false)
150
+ // WebSocket logging (default: false)
151
+ enableWebSocketLogging: false, // Track WebSocket connections and messages
152
+ logWebSocketMessages: false, // Log WebSocket message content
140
153
  // Console logging (default: false, hanya kirim ke SignOz tanpa console.log)
141
154
  enableConsoleLog: false // Set true untuk enable console.log di browser
142
155
  });
@@ -177,9 +190,11 @@ Library ini secara otomatis melog semua HTTP request dan response yang dilakukan
177
190
  4. Lihat span attributes:
178
191
  - `http.request.body`: Body dari request (untuk POST/PUT/PATCH)
179
192
  - `response.data`: Body dari response
193
+ - `response.message`: Message dari response JSON (jika ada field `message`)
180
194
  - `http.url`: URL endpoint
181
195
  - `http.method`: HTTP method
182
196
  - `http.status_code`: Status code response
197
+ - `duration_ms`: Durasi request dalam milliseconds
183
198
  - `page.url`: URL halaman frontend yang melakukan request
184
199
  - `page.pathname`: Pathname halaman frontend
185
200
  - `page.search`: Query parameters halaman frontend
@@ -303,6 +318,64 @@ initializeSignOzTracing({
303
318
  });
304
319
  ```
305
320
 
321
+ ### WebSocket Logging
322
+
323
+ Library ini otomatis track semua WebSocket connections dan messages.
324
+
325
+ **Contoh Output di Console:**
326
+ ```
327
+ [SignOz] WebSocket Connected to wss://api.example.com/ws from page /dashboard [45ms]
328
+ [SignOz] WebSocket Send to wss://api.example.com/ws from page /dashboard: {"type":"subscribe","channel":"updates"}
329
+ [SignOz] WebSocket Receive from wss://api.example.com/ws on page /dashboard: {"type":"message","data":"Hello"}
330
+ [SignOz] WebSocket Closed wss://api.example.com/ws on page /dashboard - Code: 1000, Reason: Normal closure, Clean: true
331
+ ```
332
+
333
+ **Data yang Di-track:**
334
+ - WebSocket connection (open, close, error)
335
+ - Connection duration
336
+ - Messages sent (dengan content)
337
+ - Messages received (dengan content)
338
+ - Close code dan reason
339
+ - URL halaman frontend yang membuat connection
340
+ - Message type (jika ada field `type` atau `event` di JSON)
341
+ - Message text (jika ada field `message` di JSON)
342
+
343
+ **Melihat di SignOz:**
344
+ 1. Navigasi ke **Traces**
345
+ 2. Filter by span name: "WebSocket Connection", "WebSocket Send", "WebSocket Receive", "WebSocket Close", atau "WebSocket Error"
346
+ 3. Lihat span attributes:
347
+ - `websocket.url`: URL WebSocket
348
+ - `websocket.protocols`: Protocols yang digunakan
349
+ - `websocket.state`: State connection (open, closed, error)
350
+ - `websocket.direction`: Arah message (send/receive)
351
+ - `websocket.message`: Content message
352
+ - `websocket.message.type`: Tipe message (jika ada)
353
+ - `websocket.message.text`: Text message (jika ada field `message`)
354
+ - `websocket.close.code`: Close code
355
+ - `websocket.close.reason`: Alasan close
356
+ - `websocket.close.wasClean`: Apakah close dengan clean
357
+ - `duration_ms`: Durasi connection
358
+ - `page.url`: URL halaman frontend
359
+ - `page.pathname`: Pathname halaman frontend
360
+
361
+ **Mengaktifkan WebSocket Logging:**
362
+ ```typescript
363
+ // WebSocket logging disabled by default
364
+ // Untuk mengaktifkan:
365
+ initializeSignOzTracing({
366
+ // ... konfigurasi lainnya
367
+ enableWebSocketLogging: true,
368
+ logWebSocketMessages: true // Enable message logging
369
+ });
370
+
371
+ // Atau hanya track connection tanpa log messages
372
+ initializeSignOzTracing({
373
+ // ... konfigurasi lainnya
374
+ enableWebSocketLogging: true,
375
+ logWebSocketMessages: false // Hanya track connection, tidak log messages
376
+ });
377
+ ```
378
+
306
379
  ### Error Boundary
307
380
 
308
381
  #### Penggunaan Dasar
@@ -461,6 +534,8 @@ Inisialisasi SignOz tracing untuk aplikasi React.
461
534
  - `enableErrorTracking` (opsional): Aktifkan automatic error tracking (default: true)
462
535
  - `enableNavigationTracking` (opsional): Aktifkan navigation/route tracking (default: false)
463
536
  - `enableConsoleLog` (opsional): Aktifkan console.log output di browser (default: false)
537
+ - `enableWebSocketLogging` (opsional): Aktifkan WebSocket connection dan message tracking (default: false)
538
+ - `logWebSocketMessages` (opsional): Log WebSocket message content (default: false)
464
539
 
465
540
  ### `ErrorBoundary`
466
541
 
package/dist/index.d.ts CHANGED
@@ -21,6 +21,8 @@ interface SignOzConfig {
21
21
  enableErrorTracking?: boolean;
22
22
  enableNavigationTracking?: boolean;
23
23
  enableConsoleLog?: boolean;
24
+ enableWebSocketLogging?: boolean;
25
+ logWebSocketMessages?: boolean;
24
26
  }
25
27
  declare global {
26
28
  interface Window {
package/dist/index.esm.js CHANGED
@@ -15350,6 +15350,16 @@ function addFetchLogging(config) {
15350
15350
  const responseData = await clonedResponse.text();
15351
15351
  const truncatedData = truncateBody(responseData, config.maxBodyLogSize);
15352
15352
  span.setAttribute('response.data', truncatedData);
15353
+ // Try to parse JSON and extract message if exists
15354
+ try {
15355
+ const jsonData = JSON.parse(responseData);
15356
+ if (jsonData.message) {
15357
+ span.setAttribute('response.message', jsonData.message);
15358
+ }
15359
+ }
15360
+ catch (e) {
15361
+ // Not JSON or no message field, ignore
15362
+ }
15353
15363
  if (config.enableConsoleLog) {
15354
15364
  console.log(`[SignOz] ${method} Response from ${url} (${response.status}) on page ${pagePath} [${Math.round(duration)}ms]:`, truncatedData);
15355
15365
  }
@@ -15432,6 +15442,16 @@ function addXHRLogging(config) {
15432
15442
  const responseData = xhr.responseText;
15433
15443
  const truncatedData = truncateBody(responseData, config.maxBodyLogSize);
15434
15444
  span.setAttribute('response.data', truncatedData);
15445
+ // Try to parse JSON and extract message if exists
15446
+ try {
15447
+ const jsonData = JSON.parse(responseData);
15448
+ if (jsonData.message) {
15449
+ span.setAttribute('response.message', jsonData.message);
15450
+ }
15451
+ }
15452
+ catch (e) {
15453
+ // Not JSON or no message field, ignore
15454
+ }
15435
15455
  if (config.enableConsoleLog) {
15436
15456
  console.log(`[SignOz] ${method} Response from ${url} (${xhr.status}) on page ${pagePath} [${Math.round(duration)}ms]:`, truncatedData);
15437
15457
  }
@@ -15585,6 +15605,169 @@ function addNavigationTracking(enableConsoleLog = false) {
15585
15605
  return result;
15586
15606
  };
15587
15607
  }
15608
+ // Fungsi untuk menambahkan WebSocket logging
15609
+ function addWebSocketLogging(config) {
15610
+ if (!config.enableWebSocketLogging)
15611
+ return;
15612
+ const OriginalWebSocket = window.WebSocket;
15613
+ window.WebSocket = function (url, protocols) {
15614
+ const ws = new OriginalWebSocket(url, protocols);
15615
+ const wsUrl = typeof url === 'string' ? url : url.toString();
15616
+ // Capture current page info
15617
+ const pageUrl = window.location.href;
15618
+ const pagePath = window.location.pathname;
15619
+ const tracer = trace.getTracer('websocket-logger');
15620
+ let connectionSpan = tracer.startSpan('WebSocket Connection');
15621
+ const connectionStartTime = performance.now();
15622
+ connectionSpan.setAttribute('websocket.url', wsUrl);
15623
+ connectionSpan.setAttribute('websocket.protocols', Array.isArray(protocols) ? protocols.join(',') : (protocols || 'none'));
15624
+ connectionSpan.setAttribute('page.url', pageUrl);
15625
+ connectionSpan.setAttribute('page.pathname', pagePath);
15626
+ // Track connection open
15627
+ const originalOnOpen = ws.onopen;
15628
+ ws.addEventListener('open', function (event) {
15629
+ const duration = performance.now() - connectionStartTime;
15630
+ connectionSpan.setAttribute('websocket.state', 'open');
15631
+ connectionSpan.setAttribute('duration_ms', Math.round(duration));
15632
+ connectionSpan.setStatus({ code: SpanStatusCode.OK });
15633
+ if (config.enableConsoleLog) {
15634
+ console.log(`[SignOz] WebSocket Connected to ${wsUrl} from page ${pagePath} [${Math.round(duration)}ms]`);
15635
+ }
15636
+ connectionSpan.end();
15637
+ if (originalOnOpen) {
15638
+ originalOnOpen.call(ws, event);
15639
+ }
15640
+ });
15641
+ // Track messages sent
15642
+ const originalSend = ws.send;
15643
+ ws.send = function (data) {
15644
+ if (config.logWebSocketMessages) {
15645
+ const messageSpan = tracer.startSpan('WebSocket Send');
15646
+ const sendStartTime = performance.now();
15647
+ messageSpan.setAttribute('websocket.url', wsUrl);
15648
+ messageSpan.setAttribute('websocket.direction', 'send');
15649
+ messageSpan.setAttribute('page.url', pageUrl);
15650
+ messageSpan.setAttribute('page.pathname', pagePath);
15651
+ // Log message data
15652
+ if (typeof data === 'string') {
15653
+ const truncatedData = truncateBody(data, config.maxBodyLogSize);
15654
+ messageSpan.setAttribute('websocket.message', truncatedData);
15655
+ // Try to parse JSON and extract message if exists
15656
+ try {
15657
+ const jsonData = JSON.parse(data);
15658
+ if (jsonData.message) {
15659
+ messageSpan.setAttribute('websocket.message.text', jsonData.message);
15660
+ }
15661
+ if (jsonData.type || jsonData.event) {
15662
+ messageSpan.setAttribute('websocket.message.type', jsonData.type || jsonData.event);
15663
+ }
15664
+ }
15665
+ catch (e) {
15666
+ // Not JSON, ignore
15667
+ }
15668
+ if (config.enableConsoleLog) {
15669
+ console.log(`[SignOz] WebSocket Send to ${wsUrl} from page ${pagePath}:`, truncatedData);
15670
+ }
15671
+ }
15672
+ else {
15673
+ messageSpan.setAttribute('websocket.message', '[Binary Data]');
15674
+ messageSpan.setAttribute('websocket.message.type', 'binary');
15675
+ if (config.enableConsoleLog) {
15676
+ console.log(`[SignOz] WebSocket Send to ${wsUrl} from page ${pagePath}: [Binary Data]`);
15677
+ }
15678
+ }
15679
+ const duration = performance.now() - sendStartTime;
15680
+ messageSpan.setAttribute('duration_ms', Math.round(duration));
15681
+ messageSpan.setStatus({ code: SpanStatusCode.OK });
15682
+ messageSpan.end();
15683
+ }
15684
+ return originalSend.call(ws, data);
15685
+ };
15686
+ // Track messages received
15687
+ const originalOnMessage = ws.onmessage;
15688
+ ws.addEventListener('message', function (event) {
15689
+ if (config.logWebSocketMessages) {
15690
+ const messageSpan = tracer.startSpan('WebSocket Receive');
15691
+ messageSpan.setAttribute('websocket.url', wsUrl);
15692
+ messageSpan.setAttribute('websocket.direction', 'receive');
15693
+ messageSpan.setAttribute('page.url', pageUrl);
15694
+ messageSpan.setAttribute('page.pathname', pagePath);
15695
+ // Log message data
15696
+ if (typeof event.data === 'string') {
15697
+ const truncatedData = truncateBody(event.data, config.maxBodyLogSize);
15698
+ messageSpan.setAttribute('websocket.message', truncatedData);
15699
+ // Try to parse JSON and extract message if exists
15700
+ try {
15701
+ const jsonData = JSON.parse(event.data);
15702
+ if (jsonData.message) {
15703
+ messageSpan.setAttribute('websocket.message.text', jsonData.message);
15704
+ }
15705
+ if (jsonData.type || jsonData.event) {
15706
+ messageSpan.setAttribute('websocket.message.type', jsonData.type || jsonData.event);
15707
+ }
15708
+ }
15709
+ catch (e) {
15710
+ // Not JSON, ignore
15711
+ }
15712
+ if (config.enableConsoleLog) {
15713
+ console.log(`[SignOz] WebSocket Receive from ${wsUrl} on page ${pagePath}:`, truncatedData);
15714
+ }
15715
+ }
15716
+ else {
15717
+ messageSpan.setAttribute('websocket.message', '[Binary Data]');
15718
+ messageSpan.setAttribute('websocket.message.type', 'binary');
15719
+ if (config.enableConsoleLog) {
15720
+ console.log(`[SignOz] WebSocket Receive from ${wsUrl} on page ${pagePath}: [Binary Data]`);
15721
+ }
15722
+ }
15723
+ messageSpan.setStatus({ code: SpanStatusCode.OK });
15724
+ messageSpan.end();
15725
+ }
15726
+ if (originalOnMessage) {
15727
+ originalOnMessage.call(ws, event);
15728
+ }
15729
+ });
15730
+ // Track connection errors
15731
+ const originalOnError = ws.onerror;
15732
+ ws.addEventListener('error', function (event) {
15733
+ const errorSpan = tracer.startSpan('WebSocket Error');
15734
+ errorSpan.setAttribute('websocket.url', wsUrl);
15735
+ errorSpan.setAttribute('websocket.state', 'error');
15736
+ errorSpan.setAttribute('page.url', pageUrl);
15737
+ errorSpan.setAttribute('page.pathname', pagePath);
15738
+ errorSpan.recordException(new Error('WebSocket connection error'));
15739
+ errorSpan.setStatus({ code: SpanStatusCode.ERROR, message: 'WebSocket connection error' });
15740
+ if (config.enableConsoleLog) {
15741
+ console.error(`[SignOz] WebSocket Error for ${wsUrl} on page ${pagePath}`);
15742
+ }
15743
+ errorSpan.end();
15744
+ if (originalOnError) {
15745
+ originalOnError.call(ws, event);
15746
+ }
15747
+ });
15748
+ // Track connection close
15749
+ const originalOnClose = ws.onclose;
15750
+ ws.addEventListener('close', function (event) {
15751
+ const closeSpan = tracer.startSpan('WebSocket Close');
15752
+ closeSpan.setAttribute('websocket.url', wsUrl);
15753
+ closeSpan.setAttribute('websocket.state', 'closed');
15754
+ closeSpan.setAttribute('websocket.close.code', event.code);
15755
+ closeSpan.setAttribute('websocket.close.reason', event.reason || 'No reason provided');
15756
+ closeSpan.setAttribute('websocket.close.wasClean', event.wasClean);
15757
+ closeSpan.setAttribute('page.url', pageUrl);
15758
+ closeSpan.setAttribute('page.pathname', pagePath);
15759
+ if (config.enableConsoleLog) {
15760
+ console.log(`[SignOz] WebSocket Closed ${wsUrl} on page ${pagePath} - Code: ${event.code}, Reason: ${event.reason || 'No reason'}, Clean: ${event.wasClean}`);
15761
+ }
15762
+ closeSpan.setStatus({ code: SpanStatusCode.OK });
15763
+ closeSpan.end();
15764
+ if (originalOnClose) {
15765
+ originalOnClose.call(ws, event);
15766
+ }
15767
+ });
15768
+ return ws;
15769
+ };
15770
+ }
15588
15771
  /**
15589
15772
  * Inisialisasi SignOz tracing untuk aplikasi React
15590
15773
  * @param config - Konfigurasi SignOz (opsional, akan menggunakan environment variables jika tidak disediakan)
@@ -15616,7 +15799,9 @@ function initializeSignOzTracing(config) {
15616
15799
  enableDocumentLoad: (config === null || config === void 0 ? void 0 : config.enableDocumentLoad) !== undefined ? config.enableDocumentLoad : (getConfigValue('REACT_APP_SIGNOZ_ENABLE_DOCUMENT_LOAD') === 'true'),
15617
15800
  enableErrorTracking: (config === null || config === void 0 ? void 0 : config.enableErrorTracking) !== undefined ? config.enableErrorTracking : (getConfigValue('REACT_APP_SIGNOZ_ENABLE_ERROR_TRACKING') !== 'false'),
15618
15801
  enableNavigationTracking: (config === null || config === void 0 ? void 0 : config.enableNavigationTracking) !== undefined ? config.enableNavigationTracking : (getConfigValue('REACT_APP_SIGNOZ_ENABLE_NAVIGATION_TRACKING') === 'true'),
15619
- enableConsoleLog: (config === null || config === void 0 ? void 0 : config.enableConsoleLog) !== undefined ? config.enableConsoleLog : (getConfigValue('REACT_APP_SIGNOZ_ENABLE_CONSOLE_LOG') === 'true')
15802
+ enableConsoleLog: (config === null || config === void 0 ? void 0 : config.enableConsoleLog) !== undefined ? config.enableConsoleLog : (getConfigValue('REACT_APP_SIGNOZ_ENABLE_CONSOLE_LOG') === 'true'),
15803
+ enableWebSocketLogging: (config === null || config === void 0 ? void 0 : config.enableWebSocketLogging) !== undefined ? config.enableWebSocketLogging : (getConfigValue('REACT_APP_SIGNOZ_ENABLE_WEBSOCKET_LOGGING') === 'true'),
15804
+ logWebSocketMessages: (config === null || config === void 0 ? void 0 : config.logWebSocketMessages) !== undefined ? config.logWebSocketMessages : (getConfigValue('REACT_APP_SIGNOZ_LOG_WEBSOCKET_MESSAGES') === 'true')
15620
15805
  };
15621
15806
  // Validasi konfigurasi
15622
15807
  const { isValid, missingFields } = validateConfig(effectiveConfig);
@@ -15704,6 +15889,15 @@ function initializeSignOzTracing(config) {
15704
15889
  if (effectiveConfig.enableNavigationTracking) {
15705
15890
  addNavigationTracking(effectiveConfig.enableConsoleLog);
15706
15891
  }
15892
+ // Tambahkan WebSocket logging
15893
+ if (effectiveConfig.enableWebSocketLogging) {
15894
+ addWebSocketLogging({
15895
+ enableWebSocketLogging: effectiveConfig.enableWebSocketLogging,
15896
+ logWebSocketMessages: effectiveConfig.logWebSocketMessages,
15897
+ maxBodyLogSize: effectiveConfig.maxBodyLogSize,
15898
+ enableConsoleLog: effectiveConfig.enableConsoleLog
15899
+ });
15900
+ }
15707
15901
  console.log('SignOz: Konfigurasi tracing:', {
15708
15902
  serviceName: effectiveConfig.serviceName,
15709
15903
  environment: effectiveConfig.environment,
@@ -15715,7 +15909,9 @@ function initializeSignOzTracing(config) {
15715
15909
  maxBodyLogSize: effectiveConfig.maxBodyLogSize,
15716
15910
  enableDocumentLoad: effectiveConfig.enableDocumentLoad,
15717
15911
  enableErrorTracking: effectiveConfig.enableErrorTracking,
15718
- enableNavigationTracking: effectiveConfig.enableNavigationTracking
15912
+ enableNavigationTracking: effectiveConfig.enableNavigationTracking,
15913
+ enableWebSocketLogging: effectiveConfig.enableWebSocketLogging,
15914
+ logWebSocketMessages: effectiveConfig.logWebSocketMessages
15719
15915
  });
15720
15916
  console.log('SignOz: Tracing berhasil diinisialisasi');
15721
15917
  }