SDKs
JavaScript
API Reference

API Reference

Full reference for all exported functions from @statly/observe.

Initialization

init(options)

Initialize the SDK. Call once at application startup.

function init(options: StatlyOptions): void

Parameters:

Example:

import { init } from '@statly/observe';
 
init({
  dsn: 'https://sk_live_xxx@statly.live/your-org',
  environment: 'production',
});

Capturing Events

captureException(error, context?)

Capture an error or exception.

function captureException(
  error: Error | unknown,
  context?: Record<string, unknown>
): string

Parameters:

  • error - The error to capture
  • context - Optional additional context

Returns: Event ID (UUID string)

Example:

import { captureException } from '@statly/observe';
 
try {
  riskyOperation();
} catch (error) {
  const eventId = captureException(error, {
    operation: 'riskyOperation',
    userId: currentUser.id,
  });
  console.log('Captured event:', eventId);
}

captureMessage(message, level?)

Capture a message event.

function captureMessage(
  message: string,
  level?: 'debug' | 'info' | 'warning' | 'error' | 'fatal'
): string

Parameters:

  • message - Message text
  • level - Severity level (default: 'info')

Returns: Event ID

Example:

import { captureMessage } from '@statly/observe';
 
captureMessage('User completed onboarding', 'info');
captureMessage('Payment processing slow', 'warning');
captureMessage('Database connection lost', 'fatal');

Context Management

setUser(user)

Set user context for all future events.

function setUser(user: User | null): void
 
interface User {
  id?: string;
  email?: string;
  username?: string;
  name?: string;
  [key: string]: unknown; // Custom fields
}

Example:

import { setUser } from '@statly/observe';
 
// Set user after login
setUser({
  id: 'user_123',
  email: 'jane@example.com',
  username: 'janedoe',
  plan: 'enterprise', // Custom field
});
 
// Clear user on logout
setUser(null);

setTag(key, value)

Set a single tag.

function setTag(key: string, value: string): void

Example:

import { setTag } from '@statly/observe';
 
setTag('feature', 'checkout');
setTag('experiment', 'new_ui');

setTags(tags)

Set multiple tags at once.

function setTags(tags: Record<string, string>): void

Example:

import { setTags } from '@statly/observe';
 
setTags({
  region: 'us-east-1',
  service: 'payment-api',
  version: '2.1.0',
});

Breadcrumbs

addBreadcrumb(breadcrumb)

Add a breadcrumb to the trail.

function addBreadcrumb(breadcrumb: Omit<Breadcrumb, 'timestamp'>): void
 
interface Breadcrumb {
  message?: string;
  category?: string;
  level?: 'debug' | 'info' | 'warning' | 'error';
  data?: Record<string, unknown>;
  timestamp?: number; // Auto-set
}

Example:

import { addBreadcrumb } from '@statly/observe';
 
// Navigation
addBreadcrumb({
  category: 'navigation',
  message: 'User navigated to /checkout',
  level: 'info',
});
 
// User action
addBreadcrumb({
  category: 'user',
  message: 'Clicked "Submit Order"',
  level: 'info',
  data: { orderId: 'ord_123' },
});
 
// API call
addBreadcrumb({
  category: 'http',
  message: 'POST /api/orders',
  level: 'info',
  data: { status: 201, duration: 245 },
});

Lifecycle

flush()

Wait for all pending events to be sent.

function flush(): Promise<void>

Example:

import { flush, captureMessage } from '@statly/observe';
 
captureMessage('Important event');
await flush(); // Wait for event to be sent
process.exit(0);

close()

Flush pending events and shut down the SDK.

function close(): Promise<void>

Example:

import { close } from '@statly/observe';
 
// Before server shutdown
process.on('SIGTERM', async () => {
  await close();
  process.exit(0);
});

getClient()

Get the SDK client instance.

function getClient(): StatlyClient | null

Example:

import { getClient } from '@statly/observe';
 
const client = getClient();
if (client) {
  console.log('SDK is initialized');
}

Types

StatlyOptions

interface StatlyOptions {
  dsn: string;
  environment?: string;
  release?: string;
  debug?: boolean;
  sampleRate?: number;
  maxBreadcrumbs?: number;
  autoCapture?: boolean;
  captureConsole?: boolean;
  tags?: Record<string, string>;
  beforeSend?: (event: StatlyEvent) => StatlyEvent | null;
}

StatlyEvent

interface StatlyEvent {
  message: string;
  timestamp?: number;
  level?: 'debug' | 'info' | 'warning' | 'error' | 'fatal';
  stack?: string;
  exception?: {
    type?: string;
    value?: string;
    stacktrace?: { frames?: StackFrame[] };
  };
  environment?: string;
  release?: string;
  url?: string;
  user?: User;
  tags?: Record<string, string>;
  extra?: Record<string, unknown>;
  breadcrumbs?: Breadcrumb[];
  browser?: { name?: string; version?: string };
  os?: { name?: string; version?: string };
  sdk?: { name: string; version: string };
}

User

interface User {
  id?: string;
  email?: string;
  username?: string;
  name?: string;
  [key: string]: unknown;
}

Breadcrumb

interface Breadcrumb {
  timestamp?: number;
  category?: string;
  message?: string;
  level?: 'debug' | 'info' | 'warning' | 'error';
  data?: Record<string, unknown>;
}

Logger

The Logger class provides structured logging with automatic scrubbing, batching, and session management.

Logger.create(options)

Create a new logger instance.

function create(options: LoggerOptions): Logger

Example:

import { Logger } from '@statly/observe';
 
const logger = Logger.create({
  dsn: 'https://sk_live_xxx@statly.live/your-org',
  environment: 'production',
  loggerName: 'api-server',
});

Logging Methods

trace(message, data?, options?)

Log at trace level (ultra-detailed debugging).

logger.trace('Entering function', { args: [1, 2, 3] });

debug(message, data?, options?)

Log at debug level.

logger.debug('Processing request', { requestId: 'req_123' });

info(message, data?, options?)

Log at info level.

logger.info('User logged in', { userId: 'user_123' });

warn(message, data?, options?)

Log at warning level.

logger.warn('Rate limit approaching', { current: 95, limit: 100 });

error(message, data?, options?)

Log at error level.

logger.error('Payment failed', { orderId: 'ord_456', error: 'Card declined' });

fatal(message, data?, options?)

Log at fatal level.

logger.fatal('Database connection lost', { host: 'db.example.com' });

audit(message, data?, options?)

Log at audit level (security/compliance).

logger.audit('User role changed', { userId: 'user_123', newRole: 'admin' });

Logger.child(options)

Create a child logger with inherited settings and additional context.

function child(options: ChildLoggerOptions): Logger

Example:

const requestLogger = logger.child({
  context: { requestId: 'req_123' },
  loggerName: 'request-handler',
});
 
requestLogger.info('Processing request'); // Includes requestId

Logger.setUser(user)

Set user context for the logger.

function setUser(user: LoggerUser): void

Example:

logger.setUser({
  id: 'user_123',
  email: 'jane@example.com',
  name: 'Jane Doe',
});

Logger.flush()

Flush all pending logs to the server.

async function flush(): Promise<void>

Example:

// Before shutdown
await logger.flush();

Logger.close()

Flush and close the logger.

async function close(): Promise<void>

Example:

process.on('SIGTERM', async () => {
  await logger.close();
  process.exit(0);
});

LoggerOptions

interface LoggerOptions {
  dsn: string;
  environment?: string;
  release?: string;
  loggerName?: string;
  sessionId?: string;          // Auto-generated if not provided
  user?: LoggerUser;
  defaultContext?: Record<string, unknown>;
  minLevel?: LogLevel;         // Minimum level to log (default: 'trace')
  sampleRates?: Partial<Record<LogLevel, number>>;
  scrubPatterns?: RegExp[];    // Additional patterns to scrub
  batchSize?: number;          // Batch size (default: 50)
  flushInterval?: number;      // Flush interval in ms (default: 5000)
  maxQueueSize?: number;       // Max queue size (default: 1000)
}

LogLevel

type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal' | 'audit';

LoggerUser

interface LoggerUser {
  id?: string;
  email?: string;
  name?: string;
  [key: string]: unknown;
}