omnis-logger-sdk
Version:
Lightweight TypeScript SDK for error tracking and application monitoring in React Native and Web applications
282 lines (202 loc) • 8.43 kB
Markdown
# Omnis Logger SDK
A lightweight TypeScript SDK for error tracking and application monitoring in React Native and Web applications.
## Features
- **Automatic Error Tracking** - Captures JavaScript errors, unhandled promise rejections, and network failures
- **Network Monitoring** - Automatic logging of HTTP 4xx/5xx errors with request/response details
- **Data Privacy** - Built-in sensitive data masking for passwords, tokens, emails, and custom fields
- **Breadcrumb Tracking** - Contextual event trail for debugging
- **TypeScript Support** - Full type definitions included
- **Cross-Platform** - Works seamlessly in React Native and Web environments
## Getting Started
### Create a Project
To use Omnis Logger SDK, you need an API key. Visit [omnis-cloud.com](https://omnis-cloud.com) to create a project and get your API key.
Once you have your API key, proceed with the installation below.
## Installation
```bash
npm install omnis-logger-sdk
# or
yarn add omnis-logger-sdk
```
## Quick Start
```typescript
import Logger from 'omnis-logger-sdk';
// Initialize at app startup
// apiUrl is optional - defaults to https://api.omnis-cloud.com
Logger.init({
apiKey: 'your-api-key', // Get from omnis-cloud.com
environment: 'production',
platform: 'web', // or 'react-native'
version: '1.0.0',
});
```
Errors and network failures are now automatically tracked and sent to your dashboard.
**Note:** If you're using a self-hosted instance, provide the `apiUrl` parameter with your backend URL.
## API Reference
### `Logger.init(config)`
Initializes the SDK with your configuration. Should be called once at application startup.
```typescript
Logger.init({
apiKey: string; // Required: Project API key from omnis-cloud.com
apiUrl?: string; // Optional: API endpoint (defaults to https://api.omnis-cloud.com)
environment?: string; // Optional: 'development' | 'staging' | 'production'
platform?: string; // Optional: 'web' | 'react-native' | 'ios' | 'android'
version?: string; // Optional: Application version
userId?: string; // Optional: Current user identifier
enabled?: boolean; // Optional: Enable/disable logging (default: true)
sensitiveKeys?: string[]; // Optional: Additional field names to mask
});
```
**Note:** If `apiUrl` is not provided, the SDK will use the cloud platform at `https://api.omnis-cloud.com`. To use a self-hosted instance, provide your backend URL.
### `Logger.log(level, message, context?)`
Manually log an event with optional context data.
```typescript
Logger.log('error', 'Operation failed', {
action: 'user_login',
metadata: { attempt: 3 },
});
```
### `Logger.setUserId(userId)`
Associate logs with a user identifier. Useful after user authentication.
```typescript
Logger.setUserId('user-12345');
```
### `Logger.setEnabled(enabled)`
Enable or disable logging dynamically.
```typescript
Logger.setEnabled(process.env.NODE_ENV === 'production');
```
## Data Privacy
The SDK automatically masks sensitive information in logs:
- Authentication data: `password`, `token`, `apiKey`, `authorization`, `secret`
- Financial data: `creditCard`, `credit_card`, `cvv`, `ssn`, `pin`
- Personal information: Email addresses and phone numbers
You can specify additional fields to mask:
```typescript
Logger.init({
apiKey: 'your-api-key',
// apiUrl is optional - defaults to https://api.omnis-cloud.com
sensitiveKeys: ['customToken', 'secretKey'],
});
```
## Usage Examples
### React Native
```typescript
import React, { useEffect } from 'react';
import Logger from 'omnis-logger-sdk';
function App() {
useEffect(() => {
Logger.init({
apiKey: process.env.LOGGER_API_KEY,
// apiUrl is optional - omit for cloud platform, or provide for self-hosted
apiUrl: process.env.LOGGER_API_URL,
environment: __DEV__ ? 'development' : 'production',
platform: 'react-native',
version: '1.0.0',
});
}, []);
return <YourApp />;
}
```
### Web (Next.js)
```typescript
import { useEffect } from 'react';
import Logger from 'omnis-logger-sdk';
function MyApp({ Component, pageProps }) {
useEffect(() => {
Logger.init({
apiKey: process.env.NEXT_PUBLIC_LOGGER_API_KEY,
// apiUrl is optional - omit for cloud platform, or provide for self-hosted
apiUrl: process.env.NEXT_PUBLIC_LOGGER_API_URL,
environment: process.env.NODE_ENV,
platform: 'web',
});
}, []);
return <Component {...pageProps} />;
}
```
## Flow Logging - Group Related Events
Flow logging allows you to group multiple related events into a single log entry. This is perfect for tracking multi-step processes like authentication, checkout flows, or complex user journeys.
### Quick Example
```typescript
// Start a new flow
Logger.startFlow('User Authentication');
// Add events to the flow
Logger.logFlow('info', 'Login initiated');
Logger.logFlow('info', 'Credentials validated');
Logger.logFlow('info', 'Token generated');
Logger.logFlow('error', 'Session creation failed');
// Complete the flow
Logger.endFlow('error', 'Authentication failed');
```
This creates **one log entry** with all events organized chronologically, instead of cluttering your dashboard with separate logs.
### API
#### `Logger.startFlow(flowName, flowId?)`
Starts a new flow. All subsequent `logFlow()` calls will be grouped together.
```typescript
const flowId = Logger.startFlow('Payment Process');
// Returns: "flow_1234567890_abc123"
```
#### `Logger.logFlow(level, message, context?)`
Adds an event to the active flow. Events are accumulated and sent together.
```typescript
Logger.logFlow('info', 'Payment method selected', { method: 'card' });
Logger.logFlow('warn', 'Low balance detected');
Logger.logFlow('error', 'Payment declined', { reason: 'insufficient funds' });
```
#### `Logger.endFlow(level?, summaryMessage?)`
Completes the flow and sends the grouped log to your dashboard.
```typescript
// Success
Logger.endFlow('info', 'Payment completed successfully');
// Error
Logger.endFlow('error', 'Payment process failed');
```
### Real-World Example
```typescript
async function checkoutProcess(cart, user) {
Logger.startFlow('Checkout Process');
try {
Logger.logFlow('info', 'Checkout started', { itemsCount: cart.length });
// Step 1: Validate cart
await validateCart(cart);
Logger.logFlow('info', 'Cart validated');
// Step 2: Calculate shipping
const shipping = await calculateShipping(user.address);
Logger.logFlow('info', 'Shipping calculated', { cost: shipping.cost });
// Step 3: Process payment
const payment = await processPayment(cart.total + shipping.cost);
Logger.logFlow('info', 'Payment processed', { transactionId: payment.id });
// Step 4: Create order
const order = await createOrder(cart, user, payment);
Logger.logFlow('info', 'Order created', { orderId: order.id });
Logger.endFlow('info', 'Checkout completed successfully');
return order;
} catch (error) {
Logger.logFlow('error', error.message, { error });
Logger.endFlow('error', 'Checkout failed');
throw error;
}
}
```
## Additional Features
The SDK provides additional methods for advanced use cases:
- `Logger.trackNavigation(route, params?)` - Track route changes
- `Logger.trackUserAction(action, data?)` - Track user interactions
- `Logger.setAppContext(context)` - Set application context
- `Logger.leaveBreadcrumb(category, message, data?)` - Add custom breadcrumbs
- `Logger.captureReactError(error, errorInfo)` - Capture React error boundary errors
- `Logger.startFlow(flowName, flowId?)` - Start a flow to group related events
- `Logger.logFlow(level, message, context?)` - Add an event to active flow
- `Logger.endFlow(level?, summaryMessage?)` - Complete and send flow log
- `Logger.getCurrentFlow()` - Get info about active flow
Refer to the TypeScript definitions for complete API documentation.
## Requirements
- Node.js >= 14
- React Native >= 0.60 (for React Native projects)
- TypeScript >= 4.0 (optional, but recommended)
## License
MIT
## Support
- **Cloud Platform**: [omnis-cloud.com](https://omnis-cloud.com)
- **Documentation**: [GitHub Repository](https://github.com/omnis-logger/omnis-logger)
- **Issues**: [GitHub Issues](https://github.com/omnis-logger/omnis-logger/issues)