Package Exports
- meshed-monitor-sdk
- meshed-monitor-sdk/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (meshed-monitor-sdk) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
MeshedMonitor JavaScript SDK
The official JavaScript/Node.js SDK for MeshedMonitor with real-time logging, batch processing, and advanced monitoring features.
Features
- 🚀 Real-time logging with WebSocket streaming
- 📦 Batch processing for high-performance logging
- 🔄 Background sync with offline support
- 🎯 Performance tracking with transactions and spans
- 🏷️ Rich metadata and tagging support
- 🔒 Automatic retries with exponential backoff
- 🌐 Universal compatibility (Browser and Node.js)
- 📊 Request correlation and distributed tracing
- 🛡️ Error tracking with stack traces
- 🔧 Express.js middleware included
Installation
npm install @meshed-monitor/sdk-js
Quick Start
Basic Setup
import MeshedMonitor from '@meshed-monitor/sdk-js';
const monitor = new MeshedMonitor({
apiKey: 'your-api-key',
projectId: 'your-project-id',
environment: 'production',
debug: false
});
// Basic logging
monitor.info('Application started');
monitor.warn('This is a warning', { component: 'auth' });
monitor.error('Something went wrong', { userId: '123' });
Express.js Integration
import express from 'express';
import MeshedMonitor from '@meshed-monitor/sdk-js';
const app = express();
const monitor = new MeshedMonitor({
apiKey: process.env.MESHED_MONITOR_API_KEY,
projectId: 'my-api',
environment: process.env.NODE_ENV
});
// Add middleware for automatic request logging
app.use(monitor.expressMiddleware());
app.get('/api/users', (req, res) => {
// Access monitor through req.meshedMonitor
req.meshedMonitor.log('Fetching users', 'INFO');
try {
const users = getUsersFromDatabase();
res.json(users);
} catch (error) {
req.meshedMonitor.log('Failed to fetch users', 'ERROR', {
error: error.message
});
res.status(500).json({ error: 'Internal server error' });
}
});
Configuration Options
const monitor = new MeshedMonitor({
apiKey: 'your-api-key', // Required: Your MeshedMonitor API key
projectId: 'your-project-id', // Required: Project identifier
apiUrl: 'https://api.example.com', // Optional: Custom API endpoint
environment: 'production', // Optional: Environment (production, staging, etc.)
debug: false, // Optional: Enable debug logging
batchSize: 50, // Optional: Number of logs per batch
batchTimeout: 5000, // Optional: Max time to wait before sending batch (ms)
maxRetries: 3, // Optional: Number of retry attempts
retryDelay: 1000, // Optional: Initial retry delay (ms)
enableBackgroundSync: true // Optional: Enable offline queue
});
API Reference
Logging Methods
// Basic logging with levels
monitor.debug('Debug message');
monitor.info('Info message');
monitor.warn('Warning message');
monitor.error('Error message');
// Advanced logging with metadata
monitor.info('User logged in', {
userId: '123',
email: 'user@example.com',
source: 'auth-service',
tags: { feature: 'login', version: '1.2.0' }
});
Error Tracking
try {
throwError();
} catch (error) {
// Automatic error capture with stack trace
monitor.captureError(error, {
userId: '123',
operation: 'database-query',
query: 'SELECT * FROM users'
});
}
Performance Monitoring
// Track transactions and spans
const transaction = monitor.startTransaction('user-registration');
try {
// Start a span for database operation
const dbSpan = transaction.startSpan('database-insert');
await createUserInDatabase(userData);
dbSpan.finish();
// Start a span for email sending
const emailSpan = transaction.startSpan('send-welcome-email');
await sendWelcomeEmail(userData.email);
emailSpan.finish();
} finally {
transaction.finish(); // This logs the total transaction time
}
Context Management
// Set user context
monitor.setUser({
id: '123',
email: 'user@example.com',
name: 'John Doe'
});
// Set global tags
monitor.setTags({
version: '1.2.0',
feature: 'premium'
});
// Set release version
monitor.setRelease('v1.2.0');
// Set request correlation IDs
monitor.setRequestContext('req-123', 'trace-456');
Function Wrapping
// Automatically monitor any async function
const monitoredFunction = monitor.wrap(async (userId) => {
const user = await database.getUser(userId);
return user;
}, 'getUserById');
// Usage - automatically logs performance and errors
const user = await monitoredFunction('123');
Batch Processing
The SDK automatically batches logs for optimal performance:
// These logs will be batched together
for (let i = 0; i < 100; i++) {
monitor.info(`Processing item ${i}`);
}
// Force flush the current batch
await monitor.flush();
Real-time Streaming
Logs are automatically streamed to your MeshedMonitor dashboard in real-time when using the new streaming endpoints:
// All logs automatically stream to connected dashboard clients
monitor.info('This appears in real-time on your dashboard');
Advanced Features
Background Sync
The SDK queues logs when offline and syncs them when connectivity is restored:
// Even if the network is down, logs are queued
monitor.info('This will be sent when network is available');
Request Correlation
Trace requests across multiple services:
// In your API gateway
app.use((req, res, next) => {
const traceId = req.headers['x-trace-id'] || generateTraceId();
monitor.setRequestContext(generateRequestId(), traceId);
next();
});
// In your microservice
monitor.info('Processing payment', {
// traceId is automatically included
amount: 100,
currency: 'USD'
});
Health Checks
// Check SDK connectivity
const isHealthy = await monitor.healthCheck();
if (!isHealthy) {
console.warn('MeshedMonitor is not reachable');
}
Environment Variables
You can configure the SDK using environment variables:
MESHED_MONITOR_API_KEY=your-api-key
MESHED_MONITOR_API_URL=https://your-instance.com/api
NODE_ENV=production
Best Practices
1. Use Appropriate Log Levels
monitor.debug('Detailed debugging info'); // Development only
monitor.info('General information'); // Normal operations
monitor.warn('Something unusual happened'); // Potential issues
monitor.error('Something failed'); // Errors that need attention
2. Add Meaningful Context
monitor.info('Payment processed', {
userId: '123',
amount: 99.99,
currency: 'USD',
paymentMethod: 'stripe',
tags: { feature: 'checkout' }
});
3. Use Transactions for Performance Tracking
const transaction = monitor.startTransaction('checkout-flow');
// Track each step
const validateSpan = transaction.startSpan('validate-cart');
await validateCart();
validateSpan.finish();
const paymentSpan = transaction.startSpan('process-payment');
await processPayment();
paymentSpan.finish();
transaction.finish(); // Logs total checkout time
4. Handle Cleanup Properly
// In your application shutdown
process.on('SIGTERM', async () => {
await monitor.flush(); // Send any remaining logs
monitor.destroy(); // Clean up resources
process.exit(0);
});
Browser Support
The SDK works in modern browsers with fetch support:
<script type="module">
import MeshedMonitor from './node_modules/@meshed-monitor/sdk-js/index.js';
const monitor = new MeshedMonitor({
apiKey: 'your-api-key',
projectId: 'frontend-app',
environment: 'production'
});
monitor.info('Page loaded');
window.addEventListener('error', (event) => {
monitor.captureError(event.error);
});
</script>
Migration from v0.x
If you're upgrading from an older version:
// Old way
monitor.captureMessage('Hello', 'info');
// New way
monitor.info('Hello');
Troubleshooting
Common Issues
- Logs not appearing: Check your API key and network connectivity
- High memory usage: Reduce batchSize or batchTimeout
- Performance impact: Enable batch processing and background sync
Debug Mode
Enable debug logging to troubleshoot:
const monitor = new MeshedMonitor({
apiKey: 'your-api-key',
debug: true // This will log SDK activity to console
});
License
MIT
Support
- Documentation: https://docs.meshedmonitor.com
- Issues: GitHub Issues
- Community: Discord