# 📦 GT Error Tracker SDK

Self-hosted error tracking that you own forever. No monthly fees, no usage limits.

## 🚀 Installation

```bash
npm install gt-error-tracker
```

## 📖 Quick Start

### Basic Usage

```javascript
import GTErrorTracker from 'gt-error-tracker';

// Initialize
GTErrorTracker.init({
  apiKey: 'gt_your_api_key_here',
  apiUrl: 'https://api.gideonstechnology.com',
  environment: 'production'
});

// Errors are now automatically tracked!
```

### Manual Error Tracking

```javascript
// Track exceptions
try {
  riskyOperation();
} catch (error) {
  GTErrorTracker.captureException(error, {
    tags: { feature: 'checkout' },
    extra: { orderId: '12345' }
  });
}

// Track messages
GTErrorTracker.captureMessage('Payment processed', 'info', {
  tags: { category: 'payment' }
});
```

### User Context

```javascript
// Set user information
GTErrorTracker.setUser({
  id: '123',
  email: 'user@example.com',
  username: 'john_doe'
});
```

### Breadcrumbs

```javascript
// Add breadcrumbs to track user actions
GTErrorTracker.addBreadcrumb({
  message: 'User clicked checkout button',
  category: 'user-action',
  level: 'info',
  data: { cartTotal: 99.99 }
});
```

### Custom Tags

```javascript
// Set tags for filtering
GTErrorTracker.setTags({
  version: '1.2.3',
  region: 'us-east'
});

// Or set individual tags
GTErrorTracker.setTag('feature', 'premium');
```

### 🎯 Enhanced Error Tracking (NEW)

**Request/Response Context**
```javascript
// Track errors with HTTP request/response details
try {
  await apiCall();
} catch (error) {
  GTErrorTracker.captureException(error, {
    request: {
      method: req.method,
      url: req.url,
      headers: req.headers,
      query: req.query,
      body: req.body,
      ip: req.ip
    },
    response: {
      statusCode: 500,
      statusMessage: 'Internal Server Error',
      responseTime: '1250ms'
    }
  });
}
```

**Custom Context**
```javascript
// Set application-wide context
GTErrorTracker.setContext({
  appVersion: '2.1.0',
  buildNumber: '1234',
  deployment: 'aws-us-east-1'
});

// Clear context when needed
GTErrorTracker.clearContext();
```

**Performance Tracking**
```javascript
// Track performance metrics
const start = Date.now();
await heavyOperation();
const duration = Date.now() - start;

GTErrorTracker.trackPerformance('heavy_operation', duration, 'ms');
```

**Parsed Stack Traces**
```javascript
// Stack traces are automatically parsed into structured format:
// {
//   function: 'processPayment',
//   filename: '/src/payment.js',
//   lineno: 42,
//   colno: 15
// }
```

## ⚙️ Configuration Options

```javascript
GTErrorTracker.init({
  // Required
  apiKey: 'gt_your_api_key_here',
  
  // Optional
  apiUrl: 'https://api.gideonstechnology.com', // API endpoint
  environment: 'production',                   // Environment name
  autoCapture: true,                           // Auto-capture errors
  breadcrumbsEnabled: true,                    // Enable breadcrumbs
  maxBreadcrumbs: 50                          // Max breadcrumbs to keep
});
```

## 🎯 API Reference

### `GTErrorTracker.init(options)`
Initialize the tracker with your configuration.

### `GTErrorTracker.captureException(error, options)`
Manually capture an exception.

### `GTErrorTracker.captureMessage(message, level, options)`
Capture a message. Level can be: `'info'`, `'warning'`, `'error'`.

### `GTErrorTracker.addBreadcrumb(breadcrumb)`
Add a breadcrumb to track user actions.

### `GTErrorTracker.setUser(user)`
Set user context for error reports.

### `GTErrorTracker.setTags(tags)`
Set custom tags for filtering and grouping.

### `GTErrorTracker.setEnabled(enabled)`
Enable/disable error tracking.

## 📦 React Integration

```javascript
import { useEffect } from 'react';
import GTErrorTracker from 'gt-error-tracker';

function App() {
  useEffect(() => {
    GTErrorTracker.init({
      apiKey: process.env.REACT_APP_GT_API_KEY,
      environment: process.env.NODE_ENV
    });
  }, []);

  return <YourApp />;
}
```

### Error Boundary

```javascript
import React from 'react';
import GTErrorTracker from 'gt-error-tracker';

class ErrorBoundary extends React.Component {
  componentDidCatch(error, errorInfo) {
    GTErrorTracker.captureException(error, {
      extra: errorInfo
    });
  }

  render() {
    return this.props.children;
  }
}
```

## 🌐 Node.js/Express Integration

```javascript
const GTErrorTracker = require('gt-error-tracker');

GTErrorTracker.init({
  apiKey: process.env.GT_API_KEY,
  environment: process.env.NODE_ENV
});

// Enhanced Express middleware with full request/response tracking
app.use((err, req, res, next) => {
  const startTime = req._startTime || Date.now();
  const responseTime = Date.now() - startTime;
  
  GTErrorTracker.captureException(err, {
    tags: { 
      route: req.path,
      method: req.method
    },
    request: {
      method: req.method,
      url: req.originalUrl,
      headers: req.headers,
      query: req.query,
      body: req.body,
      ip: req.ip
    },
    response: {
      statusCode: err.statusCode || 500,
      responseTime: `${responseTime}ms`
    },
    user: req.user ? {
      id: req.user.id,
      email: req.user.email
    } : undefined
  });
  
  next(err);
});

// Performance monitoring middleware
app.use((req, res, next) => {
  req._startTime = Date.now();
  next();
});
```

## 💡 Best Practices

1. **Initialize early**: Call `init()` as soon as possible in your app
2. **Set user context**: Always set user info when available
3. **Use breadcrumbs**: Track important user actions
4. **Add tags**: Tag errors for easy filtering
5. **Disable in development**: Set `enabled: false` for local dev

## 🔒 Privacy & Security

- All data stays on **your server**
- **No third-party tracking**
- **Full data ownership**
- **GDPR compliant** by design

## 📖 Full Documentation

Visit [https://gideonstechnology.com/docs/error-tracker](https://gideonstechnology.com/docs/error-tracker)

## 🆘 Support

- Email: support@gideonstechnology.com
- GitHub Issues: [github.com/gideonstechnology/gt-error-tracker/issues](https://github.com/gideonstechnology/gt-error-tracker/issues)
- Documentation: [gideonstechnology.com/docs](https://gideonstechnology.com/docs)

## 📄 License

MIT License - Pay once, use forever!

## 🎉 Get Started

1. **Purchase**: [https://gideonstechnology.com/products/error-tracker](https://gideonstechnology.com/products/error-tracker)
2. **Create Project**: Dashboard → Create New Project
3. **Get API Key**: Copy your API key
4. **Install SDK**: `npm install gt-error-tracker`
5. **Initialize**: Add to your app
6. **Track Errors**: Done! 🎊

---

Made with ❤️ by [Gideons Technology](https://gideonstechnology.com)
