@meshed-monitor/sdk
Version:
Official JavaScript/TypeScript SDK for MeshedMonitor - All-in-one monitoring platform. Supports both CommonJS and ES Modules.
268 lines (210 loc) • 5.97 kB
Markdown
# MeshedMonitor JavaScript SDK
The official JavaScript SDK for MeshedMonitor - All-in-one monitoring platform.
## Installation
```bash
npm install @meshed-monitor/sdk
# or
yarn add @meshed-monitor/sdk
# or
pnpm add @meshed-monitor/sdk
```
## Quick Start
```javascript
import MeshedMonitor from '@meshed-monitor/sdk';
// Initialize the SDK
const monitor = new MeshedMonitor({
apiKey: 'your-api-key',
projectId: 'your-project-id',
environment: 'production',
});
// Capture errors automatically
// The SDK will automatically capture unhandled errors and promise rejections
// Manually capture errors
try {
// Your code here
} catch (error) {
monitor.captureError(error, {
user: { id: '123', email: 'user@example.com' },
customData: { feature: 'checkout' }
});
}
// Track custom metrics
monitor.trackMetric({
name: 'api.response_time',
value: 125,
unit: 'ms',
tags: { endpoint: '/api/users', method: 'GET' }
});
// Monitor performance
const transaction = monitor.startTransaction('page_load');
// ... your code ...
transaction.finish();
// Set user context
monitor.setUser({
id: '123',
email: 'user@example.com',
name: 'John Doe'
});
```
## CommonJS and ESM Support
This SDK supports both CommonJS and ES Modules:
```javascript
// CommonJS
const MeshedMonitor = require('@meshed-monitor/sdk');
// ES Modules
import MeshedMonitor from '@meshed-monitor/sdk';
```
## Features
### Error Tracking
Automatically captures:
- Unhandled errors (browser and Node.js)
- Unhandled promise rejections
- Console errors (optional)
```javascript
// Capture exceptions (appears in Error Tracking)
try {
// Your code here
} catch (error) {
monitor.captureException(error, {
tags: { feature: 'checkout' },
userId: '123'
});
}
// Manual error capture (appears in Error Tracking)
monitor.captureError({
message: 'Payment processing failed',
level: 'ERROR',
tags: { payment_method: 'stripe' },
context: { orderId: '12345' }
});
// Note: monitor.error() sends to Logs, not Error Tracking
monitor.error('This appears in logs only');
```
### Logging
Stream logs from your application in real-time:
```javascript
// Log at different levels
monitor.debug('Debug information', { userId: '123' });
monitor.info('User logged in', { email: 'user@example.com' });
monitor.warn('API rate limit approaching', { remaining: 10 });
monitor.error('Failed to process payment', { orderId: '12345' });
// Generic log method
monitor.log('INFO', 'Custom log message', {
feature: 'checkout',
action: 'payment_processed'
});
```
Logs are automatically batched and sent to the API every 5 seconds or when the batch size reaches 50 logs.
### Metric Tracking
Track custom metrics from your application:
```javascript
// Track a single metric
await monitor.trackMetric({
name: 'api.response_time',
value: 125,
unit: 'ms',
tags: { endpoint: '/api/users', method: 'GET' }
});
// Track system metrics
await monitor.trackMetric({
name: 'system.cpu.usage',
value: 45.5,
unit: 'percent',
tags: { hostname: 'web-01' }
});
// Track business metrics
await monitor.trackMetric({
name: 'orders.completed',
value: 1,
aggregationType: 'sum',
tags: { region: 'us-east-1', product: 'premium' }
});
// Batch track multiple metrics
await monitor.trackMetrics([
{ name: 'memory.used', value: 1024, unit: 'MB' },
{ name: 'memory.free', value: 512, unit: 'MB' },
{ name: 'disk.usage', value: 85, unit: 'percent' }
]);
```
### Custom Metrics
Track business and technical metrics:
```javascript
// Track counters
monitor.trackMetric({
name: 'user.signup',
value: 1,
tags: { plan: 'premium' }
});
// Track gauges
monitor.trackMetric({
name: 'queue.size',
value: 42,
tags: { queue: 'email' }
});
// Track timings
monitor.trackMetric({
name: 'db.query.time',
value: 23.5,
unit: 'ms',
tags: { query: 'getUserById' }
});
```
### Monitor Health Checks
Report the status of your monitors:
```javascript
// For custom health checks
const checkResult = await performHealthCheck();
await monitor.reportCheck('monitor-id', {
success: checkResult.healthy,
responseTime: checkResult.duration,
statusCode: checkResult.statusCode,
error: checkResult.error
});
```
## Configuration
```javascript
const monitor = new MeshedMonitor({
// Required
apiKey: 'your-api-key',
// Optional
apiUrl: 'https://api.meshedmonitor.com', // Default
projectId: 'your-project-id',
environment: 'production', // Default: 'production'
debug: true, // Enable debug logging, default: false
enableLogStreaming: true, // Enable log streaming, default: true
maxBatchSize: 50, // Max logs to batch before sending, default: 50
flushInterval: 5000, // Flush interval in ms, default: 5000
});
```
## API Reference
### `MeshedMonitor`
#### Constructor
- `new MeshedMonitor(config: MeshedMonitorConfig)`
#### Methods
- `captureError(error: Error | string, context?: object): void`
- `captureWarning(message: string, context?: object): void`
- `setUser(user: { id?: string, email?: string, name?: string }): void`
- `trackMetric(metric: CustomMetric): void`
- `startTransaction(name: string): Transaction`
- `reportCheck(monitorId: string, result: MonitorCheckResult): Promise<void>`
- `log(level: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR', message: string, context?: object): void`
- `debug(message: string, context?: object): void`
- `info(message: string, context?: object): void`
- `warn(message: string, context?: object): void`
- `error(message: string, context?: object): void`
- `flush(): Promise<void>` - Manually flush queued data (including logs)
- `destroy(): void` - Clean up and stop background processes
### `Transaction`
#### Methods
- `startSpan(name: string): Span`
- `finish(): void`
### `Span`
#### Methods
- `finish(): void`
## Browser Support
- Chrome, Firefox, Safari, Edge (latest 2 versions)
- Internet Explorer 11 (with polyfills)
## Node.js Support
- Node.js 14+
## License
MIT