0
# Monitoring and Sessions
1
2
Built-in support for cron job monitoring and session tracking.
3
4
## Capabilities
5
6
### Cron Job Monitoring
7
8
Monitor cron jobs and scheduled tasks with automatic check-ins.
9
10
```typescript { .api }
11
/**
12
* Execute a function with monitor tracking and automatic check-ins
13
* @param monitorSlug - Unique identifier for the monitor
14
* @param callback - Function to execute
15
* @param upsertMonitorConfig - Optional monitor configuration
16
* @returns Return value of the callback function
17
*/
18
function withMonitor<T>(
19
monitorSlug: string,
20
callback: () => T,
21
upsertMonitorConfig?: MonitorConfig
22
): T;
23
24
/**
25
* Manually capture a cron check-in
26
* @param checkIn - Check-in data object
27
* @param upsertMonitorConfig - Optional monitor configuration
28
* @returns Event ID of the captured check-in
29
*/
30
function captureCheckIn(checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig): string;
31
```
32
33
**Usage Examples:**
34
35
```typescript
36
import * as Sentry from "@sentry/node";
37
38
// Monitor a cron job with automatic check-ins
39
const result = Sentry.withMonitor("daily-cleanup", () => {
40
console.log("Running daily cleanup...");
41
cleanupOldFiles();
42
processExpiredData();
43
generateReports();
44
return { processed: 1000, cleaned: 50 };
45
}, {
46
// Optional: specify expected schedule for more accurate monitoring
47
schedule: {
48
type: "crontab",
49
value: "0 2 * * *", // Daily at 2 AM
50
},
51
checkin_margin: 300, // 5 minutes margin
52
max_runtime: 3600, // 1 hour max runtime
53
});
54
55
// Monitor with error handling
56
Sentry.withMonitor("backup-task", () => {
57
try {
58
performBackup();
59
console.log("Backup completed successfully");
60
} catch (error) {
61
console.error("Backup failed:", error);
62
throw error; // Will be captured as a failed check-in
63
}
64
});
65
66
// Manual check-in management
67
const checkInId = Sentry.captureCheckIn({
68
monitorSlug: "manual-task",
69
status: "in_progress",
70
}, {
71
schedule: {
72
type: "crontab",
73
value: "0 0 * * MON", // Weekly on Monday
74
},
75
checkin_margin: 300, // 5 minutes margin
76
max_runtime: 3600, // 1 hour max runtime
77
});
78
79
try {
80
performWeeklyTask();
81
82
// Mark as successful
83
Sentry.captureCheckIn({
84
monitorSlug: "manual-task",
85
check_in_id: checkInId,
86
status: "ok",
87
});
88
} catch (error) {
89
// Mark as failed
90
Sentry.captureCheckIn({
91
monitorSlug: "manual-task",
92
check_in_id: checkInId,
93
status: "error",
94
});
95
throw error;
96
}
97
```
98
99
### Session Tracking
100
101
Track user sessions for release health monitoring.
102
103
```typescript { .api }
104
/**
105
* Start a new session
106
* @param context - Session context data
107
* @returns Session instance
108
*/
109
function startSession(context?: SessionContext): Session;
110
111
/**
112
* Capture the current session
113
* @param endSession - Whether to end the session after capturing
114
*/
115
function captureSession(endSession?: boolean): void;
116
117
/**
118
* End the current session
119
*/
120
function endSession(): void;
121
```
122
123
**Usage Examples:**
124
125
```typescript
126
import * as Sentry from "@sentry/node";
127
128
// Start a session for a user request
129
function handleUserRequest(req, res) {
130
const session = Sentry.startSession({
131
user: { id: req.user.id },
132
environment: "production",
133
});
134
135
try {
136
processRequest(req);
137
res.json({ success: true });
138
139
// Session will be marked as healthy
140
} catch (error) {
141
// Session will be marked as errored
142
throw error;
143
} finally {
144
Sentry.endSession();
145
}
146
}
147
148
// Background job session tracking
149
function runBackgroundJob() {
150
Sentry.startSession({
151
release: process.env.APP_VERSION,
152
environment: process.env.NODE_ENV,
153
});
154
155
try {
156
performBackgroundWork();
157
console.log("Background job completed");
158
} catch (error) {
159
console.error("Background job failed:", error);
160
throw error;
161
} finally {
162
Sentry.captureSession(true); // End session after capturing
163
}
164
}
165
166
// Long-running process session management
167
function startLongRunningProcess() {
168
Sentry.startSession();
169
170
// Periodically capture session health
171
setInterval(() => {
172
Sentry.captureSession(false); // Don't end session, just report health
173
}, 60000); // Every minute
174
175
process.on("SIGTERM", () => {
176
console.log("Process terminating, ending session");
177
Sentry.endSession();
178
process.exit(0);
179
});
180
}
181
```
182
183
### Profiling
184
185
CPU profiling for performance analysis.
186
187
```typescript { .api }
188
/**
189
* Start CPU profiling session
190
*/
191
function startProfiling(): void;
192
193
/**
194
* Stop CPU profiling session and return profile data
195
* @returns Profile data or null if profiling wasn't active
196
*/
197
function stopProfiling(): Profile | null;
198
```
199
200
**Usage Examples:**
201
202
```typescript
203
import * as Sentry from "@sentry/node";
204
205
// Profile a specific operation
206
function profiledOperation() {
207
Sentry.profiler.startProfiling();
208
209
try {
210
// Perform CPU-intensive work
211
performComplexCalculation();
212
processLargeDataset();
213
214
const profile = Sentry.profiler.stopProfiling();
215
if (profile) {
216
console.log("Profiling data captured");
217
}
218
} catch (error) {
219
Sentry.profiler.stopProfiling(); // Stop profiling even on error
220
throw error;
221
}
222
}
223
224
// Profile with automatic cleanup
225
function profileWithCleanup<T>(callback: () => T): T {
226
Sentry.profiler.startProfiling();
227
228
try {
229
return callback();
230
} finally {
231
const profile = Sentry.profiler.stopProfiling();
232
if (profile) {
233
console.log("Profile captured for operation");
234
}
235
}
236
}
237
```
238
239
## Types
240
241
### Cron Library Instrumentation
242
243
For existing cron libraries, use instrumentation functions to add Sentry monitoring:
244
245
```typescript { .api }
246
/**
247
* Instrument a generic cron library constructor
248
* @param OriginalCron - Original cron constructor
249
* @param monitorSlug - Monitor identifier
250
* @returns Instrumented cron constructor
251
*/
252
function instrumentCron<T>(OriginalCron: T, monitorSlug: string): T;
253
254
/**
255
* Instrument node-cron library
256
* @param nodeCron - node-cron library
257
* @returns Instrumented node-cron library
258
*/
259
function instrumentNodeCron<T>(nodeCron: T): T;
260
261
/**
262
* Instrument node-schedule library
263
* @param nodeSchedule - node-schedule library
264
* @returns Instrumented node-schedule library
265
*/
266
function instrumentNodeSchedule<T>(nodeSchedule: T): T;
267
```
268
269
These functions are available through the `cron` namespace:
270
271
```typescript
272
import * as Sentry from "@sentry/node";
273
274
// Instrument existing cron libraries
275
const CronJobWithSentry = Sentry.cron.instrumentCron(CronJob, "my-cron-job");
276
const cronWithSentry = Sentry.cron.instrumentNodeCron(require("node-cron"));
277
const scheduleWithSentry = Sentry.cron.instrumentNodeSchedule(require("node-schedule"));
278
```
279
280
### Cron Monitoring Types
281
282
```typescript { .api }
283
interface MonitorConfig {
284
/** Cron schedule */
285
schedule?: Schedule;
286
/** Timezone for the schedule */
287
timezone?: string;
288
/** Check-in margin in seconds */
289
checkin_margin?: number;
290
/** Maximum runtime in seconds */
291
max_runtime?: number;
292
/** Failure issue threshold */
293
failure_issue_threshold?: number;
294
/** Recovery threshold */
295
recovery_threshold?: number;
296
}
297
298
interface Schedule {
299
/** Schedule type */
300
type: "crontab" | "interval";
301
/** Schedule value (cron expression or interval) */
302
value: string;
303
/** Unit for interval schedules */
304
unit?: "minute" | "hour" | "day" | "week" | "month";
305
}
306
307
interface CheckIn {
308
/** Check-in ID (generated automatically) */
309
check_in_id?: string;
310
/** Check-in status */
311
status: "in_progress" | "ok" | "error";
312
/** Check-in duration in seconds */
313
duration?: number;
314
/** Monitor configuration for this check-in */
315
monitor_config?: MonitorConfig;
316
}
317
```
318
319
### Session Types
320
321
```typescript { .api }
322
interface Session {
323
/** Session ID */
324
sid: string;
325
/** Session status */
326
status: SessionStatus;
327
/** Session start time */
328
started: Date;
329
/** Session duration */
330
duration?: number;
331
/** Number of errors in session */
332
errors: number;
333
/** User information */
334
user?: User;
335
/** Release version */
336
release?: string;
337
/** Environment */
338
environment?: string;
339
}
340
341
interface SessionContext {
342
/** User information */
343
user?: User;
344
/** Release version */
345
release?: string;
346
/** Environment */
347
environment?: string;
348
/** Initial session status */
349
status?: SessionStatus;
350
}
351
352
type SessionStatus = "ok" | "exited" | "crashed" | "abnormal";
353
```
354
355
### Profiling Types
356
357
```typescript { .api }
358
interface Profile {
359
/** Profile ID */
360
profile_id: string;
361
/** Profiling data */
362
data: ProfileData;
363
/** Profile start time */
364
start_time: number;
365
/** Profile end time */
366
end_time: number;
367
/** Profile duration */
368
duration: number;
369
}
370
371
interface ProfileData {
372
/** CPU samples */
373
samples: ProfileSample[];
374
/** Stack traces */
375
stacks: ProfileStack[];
376
/** Frame information */
377
frames: ProfileFrame[];
378
}
379
380
interface ProfileSample {
381
/** Stack ID */
382
stack_id: number;
383
/** Thread ID */
384
thread_id: string;
385
/** Elapsed time */
386
elapsed_since_start_ns: number;
387
}
388
389
interface ProfileStack {
390
/** Frame IDs in the stack */
391
frame_ids: number[];
392
}
393
394
interface ProfileFrame {
395
/** Function name */
396
function?: string;
397
/** File name */
398
filename?: string;
399
/** Line number */
400
lineno?: number;
401
/** Column number */
402
colno?: number;
403
}
404
```