Repository navigation
Expand file tree
/
Copy patherrorTracking.js
More file actions
360 lines (306 loc) · 8.6 KB
/
Copy patherrorTracking.js
File metadata and controls
360 lines (306 loc) · 8.6 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/**
* Sentry Error Tracking Integration
*
* Provides comprehensive error monitoring with:
* - Automatic error capture and grouping
* - Wallet address and contract ID tracking
* - Performance monitoring
* - Discord webhook alerts for critical errors
*/
const Sentry = require('@sentry/node');
const { logger } = require('./logger');
const axios = require('axios');
class ErrorTrackingService {
constructor() {
this.initialized = false;
this.discordWebhookUrl = process.env.DISCORD_ERROR_WEBHOOK_URL;
}
/**
* Initialize Sentry SDK
*/
initialize() {
if (this.initialized) {
return;
}
const dsn = process.env.SENTRY_DSN;
if (!dsn) {
console.warn('[ErrorTracking] Sentry DSN not configured. Error tracking disabled.');
return;
}
Sentry.init({
dsn,
environment: process.env.NODE_ENV || 'development',
tracesSampleRate: process.env.SENTRY_TRACES_SAMPLE_RATE || 0.1, // 10% sampling
profilesSampleRate: process.env.SENTRY_PROFILES_SAMPLE_RATE || 0.1,
// Add contextual data to all events
beforeSend: (event, hint) => {
// Add wallet address if available
if (hint.originalException?.walletAddress) {
event.tags = {
...event.tags,
walletAddress: hint.originalException.walletAddress.toLowerCase(),
};
}
// Add contract ID if available
if (hint.originalException?.contractId) {
event.tags = {
...event.tags,
contractId: hint.originalException.contractId,
};
}
// Don't send in development unless explicitly enabled
if (process.env.NODE_ENV === 'development' && !process.env.SENTRY_ENABLE_DEV) {
return null;
}
return event;
},
// Integrations
integrations: [
// HTTP request tracing
new Sentry.Integrations.Http({ tracing: true }),
// Database query tracking
new Sentry.Integrations.Postgres(),
// Console error capture
new Sentry.Integrations.Console(),
// On-uncaught exceptions
new Sentry.Integrations.OnUncaughtException(),
// On-unhandled rejections
new Sentry.Integrations.OnUnhandledRejection(),
],
});
this.initialized = true;
console.log('[ErrorTracking] Sentry initialized successfully');
}
/**
* Capture an exception with context
* @param {Error} error - Error object
* @param {object} context - Additional context
*/
captureException(error, context = {}) {
if (!this.initialized) {
logger.error('Error occurred (Sentry not initialized)', { error: error.message, ...context });
return;
}
Sentry.withScope((scope) => {
// Set context tags
if (context.walletAddress) {
scope.setTag('walletAddress', context.walletAddress.toLowerCase());
}
if (context.contractId) {
scope.setTag('contractId', context.contractId);
}
if (context.deviceId) {
scope.setTag('deviceId', context.deviceId);
}
if (context.traceId) {
scope.setTag('traceId', context.traceId);
}
// Set additional context
scope.setContext('custom', {
operation: context.operation,
endpoint: context.endpoint,
method: context.method,
timestamp: new Date().toISOString(),
...context,
});
// Capture the exception
Sentry.captureException(error);
});
// Also log with Winston
logger.error(`Exception captured: ${error.message}`, {
error: error.message,
stack: error.stack,
...context,
});
// Check if we should send Discord alert
this._checkDiscordAlert(error, context);
}
/**
* Capture a message (for debugging/monitoring)
* @param {string} message - Message to capture
* @param {object} context - Additional context
* @param {string} level - Severity level
*/
captureMessage(message, context = {}, level = 'info') {
if (!this.initialized) {
logger[level](message, context);
return;
}
Sentry.withScope((scope) => {
if (context.walletAddress) {
scope.setTag('walletAddress', context.walletAddress.toLowerCase());
}
if (context.contractId) {
scope.setTag('contractId', context.contractId);
}
scope.setContext('custom', context);
Sentry.captureMessage(message, level);
});
logger[level](message, context);
}
/**
* Start a performance trace
* @param {string} name - Trace name
* @param {object} context - Trace context
*/
startTrace(name, context = {}) {
if (!this.initialized) {
return null;
}
const transaction = Sentry.startTransaction({
name,
op: context.op || 'function',
tags: {
walletAddress: context.walletAddress?.toLowerCase(),
contractId: context.contractId,
},
});
return transaction;
}
/**
* Set user context for error tracking
* @param {string} walletAddress - Wallet address
* @param {object} metadata - Additional user metadata
*/
setUser(walletAddress, metadata = {}) {
if (!this.initialized) {
return;
}
Sentry.setUser({
id: walletAddress.toLowerCase(),
username: walletAddress,
...metadata,
});
}
/**
* Clear user context
*/
clearUser() {
if (!this.initialized) {
return;
}
Sentry.setUser(null);
}
/**
* Check if Discord alert should be sent
* @param {Error} error - Error object
* @param {object} context - Context
*/
async _checkDiscordAlert(error, context) {
// Only alert for critical errors
const isCritical =
context.riskLevel === 'critical' ||
error.name === 'CriticalError' ||
context.forceAlert === true;
if (!isCritical || !this.discordWebhookUrl) {
return;
}
try {
await this.sendDiscordAlert(error, context);
} catch (discordError) {
logger.error('Failed to send Discord alert', {
error: discordError.message,
originalError: error.message,
});
}
}
/**
* Send alert to Discord webhook
* @param {Error} error - Error object
* @param {object} context - Context
*/
async sendDiscordAlert(error, context) {
if (!this.discordWebhookUrl) {
console.warn('[ErrorTracking] Discord webhook not configured');
return;
}
const embed = {
title: `🚨 Critical Error Alert`,
color: 15158332, // Red
timestamp: new Date().toISOString(),
fields: [
{
name: 'Error',
value: `\`${error.message}\``,
inline: false,
},
{
name: 'Type',
value: `\`${error.name}\``,
inline: true,
},
{
name: 'Environment',
value: process.env.NODE_ENV || 'development',
inline: true,
},
],
};
// Add context fields
if (context.walletAddress) {
embed.fields.push({
name: 'Wallet',
value: `\`${context.walletAddress.toLowerCase()}\``,
inline: true,
});
}
if (context.contractId) {
embed.fields.push({
name: 'Contract',
value: `\`${context.contractId}\``,
inline: true,
});
}
if (context.traceId) {
embed.fields.push({
name: 'Trace ID',
value: `\`${context.traceId}\``,
inline: true,
});
}
// Add stack trace (truncated)
if (error.stack) {
const stackLines = error.stack.split('\n').slice(0, 5).join('\n');
embed.fields.push({
name: 'Stack Trace',
value: `\`\`\`${stackLines}\`\`\``,
inline: false,
});
}
const payload = {
username: 'SubStream Error Monitor',
avatar_url: 'https://avatars.githubusercontent.com/u/123456789',
embeds: [embed],
};
await axios.post(this.discordWebhookUrl, payload, {
headers: {
'Content-Type': 'application/json',
},
});
logger.info('Discord alert sent successfully', {
error: error.message,
});
}
/**
* Flush pending events to Sentry
*/
async flush() {
if (!this.initialized) {
return;
}
await Sentry.flush(5000); // Wait up to 5 seconds
}
/**
* Close Sentry connection
*/
async close() {
if (!this.initialized) {
return;
}
await Sentry.close();
this.initialized = false;
}
}
// Export singleton instance
const errorTracking = new ErrorTrackingService();
module.exports = { ErrorTrackingService, errorTracking };