# 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

```bash
npm install @meshed-monitor/sdk-js
```

## Quick Start

### Basic Setup

```javascript
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

```javascript
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

```javascript
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

```javascript
// 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

```javascript
try {
  throwError();
} catch (error) {
  // Automatic error capture with stack trace
  monitor.captureError(error, {
    userId: '123',
    operation: 'database-query',
    query: 'SELECT * FROM users'
  });
}
```

### Performance Monitoring

```javascript
// 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

```javascript
// 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

```javascript
// 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:

```javascript
// 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:

```javascript
// 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:

```javascript
// 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:

```javascript
// 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

```javascript
// 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:

```bash
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

```javascript
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

```javascript
monitor.info('Payment processed', {
  userId: '123',
  amount: 99.99,
  currency: 'USD',
  paymentMethod: 'stripe',
  tags: { feature: 'checkout' }
});
```

### 3. Use Transactions for Performance Tracking

```javascript
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

```javascript
// 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:

```html
<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:

```javascript
// Old way
monitor.captureMessage('Hello', 'info');

// New way
monitor.info('Hello');
```

## Troubleshooting

### Common Issues

1. **Logs not appearing**: Check your API key and network connectivity
2. **High memory usage**: Reduce batchSize or batchTimeout
3. **Performance impact**: Enable batch processing and background sync

### Debug Mode

Enable debug logging to troubleshoot:

```javascript
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](https://docs.meshedmonitor.com)
- Issues: [GitHub Issues](https://github.com/meshed-cloud/meshed-monitor/issues)
- Community: [Discord](https://discord.gg/meshedmonitor)