@lognitor/browser
The Browser SDK for Lognitor. Auto-captures errors, console output, fetch/XHR requests, and session data.
Installation
npm / yarn
npm install @lognitor/browserCDN Script
<script src="$https://unpkg.com/@lognitor/browser@1.0.0/dist/umd/lognitor.min.js"></script>When loaded via CDN, all functions are available on the global Lognitor object.
Quick Start
ES Module
import Lognitor from '@lognitor/browser';
Lognitor.init({
apiKey: 'your-api-key',
service: 'my-website',
environment: 'production',
});
Lognitor.info('Page loaded', { metadata: { page: window.location.pathname } });CDN Script
<script src="$https://unpkg.com/@lognitor/browser@1.0.0/dist/umd/lognitor.min.js"></script>
<script>
Lognitor.init({
apiKey: 'your-api-key',
service: 'my-website',
environment: 'production',
});
Lognitor.info('Page loaded');
</script>Configuration
Lognitor.init({
apiKey: 'your-api-key',
service: 'my-website',
environment: 'production',
version: '2.1.0',
// Batching
batchSize: 25,
flushInterval: 5000,
maxQueueSize: 1000,
maxRetries: 3,
// Filtering
minLevel: 'info',
enabled: true,
// Privacy
redactPatterns: ['email', 'creditCard'],
scrubUrlParams: ['token', 'password', 'secret'],
// Auto-capture (browser-specific)
captureConsole: true,
captureErrors: true,
captureFetch: true,
sessionTracking: true,
ignoreErrors: [
'ResizeObserver loop limit',
/Script error/i,
],
// Advanced
autoTruncate: true,
maxBreadcrumbs: 100,
debug: false,
beforeSend: (log) => {
if (log.metadata?.page_url?.includes('/internal')) return null;
return log;
},
});Browser-Specific Options
| Option | Type | Default | Description |
|---|---|---|---|
captureConsole | boolean | true | Capture console.error and console.warn as log entries. |
captureErrors | boolean | true | Capture unhandled errors (window.onerror) and unhandled promise rejections. |
captureFetch | boolean | true | Add breadcrumbs for fetch() and XMLHttpRequest calls. |
sessionTracking | boolean | true | Auto-generate a session ID per browser tab. |
ignoreErrors | (string | RegExp)[] | [] | Error messages matching these are silently dropped. |
All other options are the same as the Node.js SDK.
Log Levels
import { debug, info, warn, error, fatal } from '@lognitor/browser';
debug('Component re-rendered', { metadata: { component: 'UserList' } });
info('Page loaded', { metadata: { url: window.location.href } });
warn('API response slow', { metadata: { duration: 3200 } });
error('Form submission failed', { error: new Error('Network error') });
fatal('App crashed');Per-Log Options
info('User clicked checkout', {
metadata: { cartItems: 3, total: 99.99 },
tags: ['checkout', 'conversion'],
action: 'checkout.click',
user: { id: 'user_123', email: 'alice@example.com' },
device: { browser: 'Chrome', os: 'macOS' },
notify: true,
notifyChannels: ['slack'],
});User Context
import { setUser, clearUser } from '@lognitor/browser';
setUser({ id: 'user_123', email: 'alice@example.com', name: 'Alice' });
info('Viewed dashboard'); // includes user context
// Override per-log
info('Admin action', { user: { id: 'admin_1' } });
// On logout
clearUser();Global Context, Tags, and Session
import { setContext, setTags, setSession } from '@lognitor/browser';
setContext({ page: '/dashboard', feature_flags: ['new-nav'] });
setTags(['premium-user']);
setSession('sess_abc123');
info('Feature used'); // includes metadata.page, tags, session_idError Capturing
Automatic
With captureErrors: true (default), the SDK automatically captures unhandled errors (window.addEventListener('error', ...)) and unhandled promise rejections (window.addEventListener('unhandledrejection', ...)).
Manual
import { captureException, error } from '@lognitor/browser';
try {
await riskyOperation();
} catch (err) {
captureException(err, {
metadata: { operation: 'riskyOperation', userId: currentUser.id },
tags: ['critical'],
});
}
error('API call failed', {
error: new TypeError('Failed to fetch'),
metadata: { endpoint: '/api/orders' },
});Console Capture
With captureConsole: true (default), console.error(...) and console.warn(...) are captured as log entries with appropriate levels.
Breadcrumbs
Automatic
With captureFetch: true (default), the SDK automatically records breadcrumbs for fetch() requests (method, URL, status, duration), XMLHttpRequest calls, and navigation events (page loads, history changes).
Manual
import { addBreadcrumb } from '@lognitor/browser';
addBreadcrumb({
type: 'user',
category: 'ui.click',
message: 'Clicked "Add to cart" button',
level: 'info',
data: { productId: 'prod_123', buttonId: '#add-to-cart' },
});Timers
import { startTimer } from '@lognitor/browser';
const timer = startTimer();
const response = await fetch('/api/heavy-report');
const data = await response.json();
timer.end('Report loaded', {
metadata: { rows: data.length },
perf: { api_calls: 1 },
});Heartbeat Monitoring
import { heartbeat } from '@lognitor/browser';
const hb = heartbeat('your-monitor-token');
await hb.ping();
const result = await hb.wrap(async () => {
return await syncData();
});User Feedback
Show a feedback dialog linked to an error event:
import { error, showReportDialog } from '@lognitor/browser';
const logId = error('Checkout failed', { error: new Error('Payment timeout') });
showReportDialog({ eventId: logId });Or submit feedback programmatically:
import { submitFeedback } from '@lognitor/browser';
await submitFeedback({
eventId: logId,
comments: 'The page froze when I clicked pay',
name: 'Alice',
email: 'alice@acme.com',
});Release Tracking
import { registerRelease } from '@lognitor/browser';
const release = await registerRelease({
version: '2.1.0',
commitHash: 'a1b2c3d4',
branch: 'main',
deployedBy: 'vercel',
});Child Loggers
import { init, child } from '@lognitor/browser';
Lognitor.init({ apiKey: 'your-key', service: 'my-app' });
const checkoutLogger = child({
service: 'checkout-flow',
metadata: { module: 'checkout' },
tags: ['checkout'],
});
checkoutLogger.info('User started checkout');
checkoutLogger.error('Payment failed', { error: new Error('Declined') });Flush, Shutdown, Pause, Resume
import { flush, shutdown, pause, resume } from '@lognitor/browser';
await flush(); // Send all buffered logs now
await shutdown(); // Flush everything and clean up
pause(); // Pause sending (still buffers)
resume(); // Resume sendingThe SDK also uses navigator.sendBeacon on page unload to flush remaining logs.
Reconfigure
import { reconfigure } from '@lognitor/browser';
reconfigure({
minLevel: 'warn',
enabled: false,
debug: true,
});Single-Page App Considerations
For SPAs (React, Vue, Angular), initialize the SDK once at app startup. Use setContext on route changes to track the current page:
import { setContext, addBreadcrumb } from '@lognitor/browser';
function onRouteChange(newPath) {
setContext({ page: newPath });
addBreadcrumb({
type: 'navigation',
category: 'route',
message: `Navigated to ${newPath}`,
level: 'info',
});
}