Full-Stack Observability SDK

Apperio SDK

Auto-instrumentation, distributed tracing, PII protection, and resilient delivery in a single TypeScript package. Like Sentry + LogRocket, but with full control.

TypeScript
React
Next.js
~50KBgzipped
<30ssetup
15+features
Get Started

Quick Start

Three steps. Any framework. Under 30 seconds.

1
Install
Terminal
Terminal
npm install apperio
Or:yarn add apperiopnpm add apperio
2
Initialize
app.ts
TypeScript
import { Apperio } from "apperio";

const logger = new Apperio({
  apiKey: "your-api-key",
  projectId: "your-project-id",
  environment: "production",
  serviceName: "my-web-app",
});
3
Log
usage.ts
TypeScript
// Manual logging (optional)
logger.info("User signed up", {
  plan: "pro",
});

// Auto-capture is already active:
// Errors, performance, network,
// page views, console, interactions
Auto-Instrumentation

7 Categories. Zero Config.

Everything captured automatically. Toggle each category on or off.

Errors
window.onerror, unhandledrejection, full stack traces
errors: true
Performance
PerformanceObserver for navigation, resource, paint timing
performance: true
Web Vitals
LCP, CLS, INP with good/needs-improvement/poor ratings
performance: true
Network
fetch/XHR interception with timing, status, request/response size
networkRequests: true
Console
console.error() and console.warn() capture with arguments
consoleMessages: true
Page Views
SPA route change detection via History API patching
pageViews: true
Interactions
Click/scroll tracking with CSS selectors, not text content
userInteractions: true
Web Vitals Thresholds
LCP< 2.5s/2.5-4s/> 4s
CLS< 0.1/0.1-0.25/> 0.25
INP< 200ms/200-500ms/> 500ms

Each metric auto-rated. Data includes URL, element, and navigation type.

auto-capture-config.ts
TypeScript
const logger = new Apperio({
  apiKey: "your-api-key",
  projectId: "your-project-id",
  autoCapture: {
    errors: true,              // Uncaught errors + promise rejections
    performance: true,         // Navigation, resource, paint timing + Web Vitals
    networkRequests: true,     // fetch/XHR with timing and size
    pageViews: true,           // SPA route changes via History API
    consoleMessages: false,    // console.error/warn (can be noisy)
    userInteractions: false,   // click/scroll tracking (verbose)
  },
});
Distributed Tracing

Trace Requests Across Services

W3C Trace Context propagation. Start spans, link operations, and follow requests from browser to backend.

Span API
Create spans to measure operations and propagate context
tracing.ts
TypeScript
// Start a span for a database query
const spanId = logger.startSpan("db-query", {
  db: "users",
  operation: "findById",
});

// ... perform the operation ...
const user = await db.users.findById(id);

// End the span (duration auto-calculated)
logger.endSpan(spanId);

// Nested spans for complex operations
const parentSpan = logger.startSpan("checkout");
  const validateSpan = logger.startSpan("validate-cart");
  // ... validate ...
  logger.endSpan(validateSpan);

  const paymentSpan = logger.startSpan("process-payment");
  // ... charge ...
  logger.endSpan(paymentSpan);
logger.endSpan(parentSpan);
W3C Trace Propagation
Automatic traceparent header injection and extraction across HTTP boundaries
propagation.ts
TypeScript
// TracePropagator automatically injects
// W3C traceparent headers into outgoing requests:
//
// traceparent: 00-{traceId}-{spanId}-01
//
// This links frontend spans to backend spans,
// enabling full request waterfall visualization.

// The SDK patches fetch() to auto-inject headers.
// No manual instrumentation needed.

Request Waterfall

Browser: checkout
API: /api/orders
DB: insert order
Stripe: charge
Privacy & Data Protection

Built-In PII Protection

9 built-in patterns, 3 presets, custom rules, and a full audit trail. GDPR-friendly by default.

Built-in Patterns
Email addresses
Phone numbers
Social Security Numbers
Credit card numbers
IP addresses
JWT tokens
API keys
Password fields
Dates of birth
Presets
STRICT

All 9 patterns + URL sanitization

BALANCED

Email, phone, SSN, credit card, passwords

LENIENT

Only passwords and credit cards

Custom Rules
sanitization.ts
TypeScript
const logger = new Apperio({
  apiKey: "your-api-key",
  projectId: "your-project-id",
  sanitization: {
    preset: "BALANCED",
    customRules: [
      {
        pattern: /ACCT-\d{8}/g,
        replacement: "[ACCOUNT_ID]",
      },
    ],
  },
});

// Audit trail access:
const trail = logger
  .getSanitizationAuditTrail();
// [{field, pattern, action, ts}]
Resilience & Reliability

Built to Never Drop Logs

Circuit breaker, offline queue, payload compression, and real-time health metrics

Circuit Breaker Pattern
Protects your app when the API is unreachable. Automatically stops sending, tests recovery, and resumes when healthy.
circuit-breaker.ts
TypeScript
const logger = new Apperio({
  apiKey: "your-api-key",
  projectId: "your-project-id",

  // Circuit breaker configuration
  circuitBreaker: {
    failureThreshold: 5,   // Open after 5 failures
    resetTimeout: 30000,   // Try again after 30s
    halfOpenRequests: 1,   // Test with 1 request
  },
});

// SDK handles state transitions automatically:
// CLOSED  -> normal operation, sending logs
// OPEN    -> API failing, logs buffered locally
// HALF_OPEN -> testing if API recovered
State Machine
CLOSED

Normal operation. Logs sent to API. Failure counter tracks errors.

OPEN

API unreachable. Logs buffered in memory. No requests sent until timeout.

HALF_OPEN

Testing recovery. One probe request sent. Success closes, failure reopens.

Transitions are automatic. Zero developer intervention needed.

Advanced Capabilities

Beyond Basic Logging

Pattern detection, remote configuration, breadcrumbs, and the enhanced logger factory

Pattern Detection
Detects recurring errors and error spikes in real-time
pattern-detection.ts
TypeScript
const logger = new Apperio({
  apiKey: "your-api-key",
  projectId: "your-project-id",
  patternDetection: {
    recurringErrors: {
      window: 60000,       // 1 minute window
      threshold: 5,        // 5 occurrences
    },
    errorSpikes: {
      baselineWindow: 300000, // 5 min baseline
      spikeMultiplier: 3,    // 3x normal rate
    },
  },
  onPatternDetected: (pattern) => {
    console.warn("Pattern:", pattern.type);
    // "recurring-error" | "error-spike"
  },
});
Remote Configuration
Change log level, sampling rate, and auto-capture toggles without redeploying
remote-config.ts
TypeScript
const logger = new Apperio({
  apiKey: "your-api-key",
  projectId: "your-project-id",

  // Remote config polling
  remoteConfigUrl: "https://your-api/config",
  remoteConfigInterval: 300000, // 5 minutes

  // Changes applied at runtime:
  // - Log level (trace -> warn)
  // - Sampling rate (100% -> 10%)
  // - Auto-capture toggles
  // - Custom rules
  // No restart needed!
});
Breadcrumb Manager
Trail of last 50 actions with environment snapshots, auto-attached to error reports
breadcrumbs.ts
TypeScript
// Add breadcrumbs manually
logger.addBreadcrumb(
  "User clicked checkout",
  "user-action",
  { cartItems: 3, total: 99.99 }
);

logger.addBreadcrumb(
  "Navigated to /checkout",
  "navigation"
);

logger.addBreadcrumb(
  "POST /api/orders succeeded",
  "network",
  { status: 201, duration: 342 }
);

// Breadcrumbs auto-included in error reports
// Categories: user-action, navigation,
// network, console, error, custom
Enhanced Logger Factory
All advanced managers in one call: context, sessions, custom events, feature flags, A/B testing
enhanced-logger.ts
TypeScript
import { createEnhancedLogger } from "apperio";

const {
  logger,
  contextManager,   // Scoped context management
  sessionManager,   // Auto session tracking
  eventTracker,     // Custom business events
  featureFlagLogger,// Feature flag tracking
  abTestLogger,     // A/B test variant logging
  performanceMonitor,// Custom perf measurements
} = createEnhancedLogger({
  apiKey: "your-api-key",
  projectId: "your-project-id",
});

// Track business events
eventTracker.track("purchase", {
  amount: 99.99, plan: "pro"
});

// Log A/B test variants
abTestLogger.logVariant(
  "pricing-test", "variant-b"
);
Interactive Demo

Try It Live

Send manual logs and simulate auto-captured events in real-time

Send Test Log
Simulate SDK logging — send manual logs or trigger auto-captured events

Simulate Auto-Capture

Live Log Stream
2 logs
Real-time log visualization with level filtering
INFOauto-captured
1:12:30 PM

Application started

{
  "version": "1.2.2",
  "environment": "demo"
}
WARNauto-captured
1:15:30 PM

High memory usage detected

{
  "usage": "85%",
  "threshold": "80%"
}
Framework SDKs

First-Class Framework Support

Dedicated packages for React and Next.js with idiomatic APIs

@apperio/react

React Context Provider, hooks, and Error Boundary

ApperioProvider
ApperioProvider.tsx
TSX
import { ApperioProvider } from "@apperio/react";

// Wrap your app root
<ApperioProvider config={{
  apiKey: "your-api-key",
  projectId: "your-project-id",
  environment: "production",
}}>
  <App />
</ApperioProvider>
Hooks
hooks.tsx
TSX
import {
  useApperio,
  useLogError,
  useTrackEvent,
  usePerformance,
} from "@apperio/react";

function MyComponent() {
  const logger = useApperio();       // Core logger
  const logError = useLogError();   // Error logging
  const track = useTrackEvent();    // Event tracking
  const perf = usePerformance();    // Perf measurement

  const handleSubmit = async () => {
    perf.start("form-submit");
    try {
      await submitForm();
      track("form_submitted", { form: "signup" });
    } catch (err) {
      logError(err, { form: "signup" });
    }
    perf.end("form-submit");
  };
}
ApperioErrorBoundary
ErrorBoundary.tsx
TSX
import { ApperioErrorBoundary }
  from "@apperio/react";

<ApperioErrorBoundary
  fallback={<ErrorPage />}
>
  <FeatureComponent />
</ApperioErrorBoundary>

// Automatically captures:
// - Error name, message, stack
// - Component tree (componentStack)
// - Breadcrumbs at time of crash

@apperio/nextjs

Middleware wrapper, server logger, and API route handler

withApperioMiddleware
middleware.ts
TypeScript
// middleware.ts
import { withApperioMiddleware }
  from "@apperio/nextjs";
import { NextResponse } from "next/server";

const middleware = (request) => {
  return NextResponse.next();
};

export default withApperioMiddleware(
  middleware,
  {
    apiKey: process.env.APPERIO_API_KEY!,
    projectId: "your-project-id",
  }
);

// Automatically logs every request:
// method, path, status, duration, user-agent
createServerLogger
server-logger.ts
TypeScript
// lib/logger.ts
import { createServerLogger }
  from "@apperio/nextjs";

export const logger = createServerLogger({
  apiKey: process.env.APPERIO_API_KEY!,
  projectId: "your-project-id",
  environment: process.env.NODE_ENV,
});

// Use in any server component or route:
import { logger } from "@/lib/logger";

export async function GET() {
  logger.info("Fetching users");
  const users = await db.users.findAll();
  return Response.json(users);
}
withApperio (Route Wrapper)
route-wrapper.ts
TypeScript
import { withApperio } from "@apperio/nextjs";

// Wraps route with auto error catching
export const GET = withApperio(
  async (request) => {
    const data = await fetchData();
    return Response.json(data);
  },
  {
    apiKey: process.env.APPERIO_API_KEY!,
    projectId: "your-project-id",
  }
);

// Errors auto-captured with:
// route, method, headers, request body
Configuration

Full Configuration Reference

Every option in LoggerConfig, documented

LoggerConfig
TypeScript
1interface LoggerConfig {
2 // Required
3 apiKey: string; // Your project API key
4 projectId: string; // Your project ID
5
6 // Identity & Environment
7 environment?: string; // "production" | "staging" | "development"
8 serviceName?: string; // Service identifier
9
10 // Log Control
11 minLogLevel?: LogLevel; // Minimum level to capture (default: TRACE)
12 batchSize?: number; // Logs per batch (default: 10)
13 flushInterval?: number; // Flush interval in ms (default: 5000)
14 maxRetries?: number; // Max retry attempts (default: 3)
15 maxBreadcrumbs?: number; // Breadcrumb trail size (default: 50)
16
17 // Auto-Capture
18 autoCapture?: {
19 errors?: boolean; // Uncaught errors (default: true)
20 performance?: boolean; // Performance + Web Vitals (default: true)
21 networkRequests?: boolean; // fetch/XHR monitoring (default: true)
22 pageViews?: boolean; // SPA route changes (default: true)
23 consoleMessages?: boolean; // console.error/warn (default: false)
24 userInteractions?: boolean; // click/scroll tracking (default: false)
25 };
26
27 // Resilience
28 circuitBreaker?: {
29 failureThreshold?: number; // Failures before open (default: 5)
30 resetTimeout?: number; // Recovery timeout ms (default: 30000)
31 halfOpenRequests?: number; // Probe requests (default: 1)
32 };
33 offlineQueue?: {
34 maxSize?: number; // Max queued logs (default: 500)
35 priorityEviction?: boolean; // Priority-based eviction (default: true)
36 };
37 compression?: boolean; // Gzip payloads (default: false)
38
39 // Privacy
40 sanitization?: {
41 preset?: "STRICT" | "BALANCED" | "LENIENT";
42 customRules?: Array<{
43 pattern: RegExp;
44 replacement: string;
45 }>;
46 };
47
48 // Pattern Detection
49 patternDetection?: {
50 recurringErrors?: { window: number; threshold: number };
51 errorSpikes?: { baselineWindow: number; spikeMultiplier: number };
52 };
53 onPatternDetected?: (pattern: DetectedPattern) => void;
54
55 // Remote Config
56 remoteConfigUrl?: string; // Config endpoint URL
57 remoteConfigInterval?: number; // Poll interval ms (default: 300000)
58
59 // Callbacks
60 onError?: (error: Error) => void; // SDK error handler
61 debug?: boolean; // Enable SDK debug logs (default: false)
62}
API Reference

Complete Method Reference

Every method on the Apperio logger instance, organized by domain

Core Logging
trace(message, data?)

Trace-level log

debug(message, data?)

Debug-level log

info(message, data?)

Info-level log

warn(message, data?)

Warning-level log

error(message, error?)

Error-level log

fatal(message, error?)

Fatal-level log

Error Capture
captureException(error, ctx?)

Structured error capture

captureMessage(msg, level, data?)

Structured message

addBreadcrumb(msg, cat?, data?)

Add breadcrumb

Distributed Tracing
startSpan(name, attrs?)

Start a trace span

endSpan(spanId)

End a trace span

Context
setContext(context)

Set global context

clearContext()

Clear global context

Lifecycle
flush()

Force flush buffer

destroy()

Cleanup and shutdown

Observability
getHealthMetrics()

SDK health stats

getSanitizationAuditTrail()

PII audit log

Ready to Start?

Full Observability in 30 Seconds

Install Apperio SDK and start capturing errors, performance, network requests, and user interactions automatically.

No credit card required
10,000 free events / month
MIT licensed, open source