npm package: @remote-logger/sdk
Description: JavaScript SDK for Remote Logger
Latest version: 0.1.8

# Remote Logger SDK

A lightweight logging SDK that sends structured logs to a Remote Logger backend via HTTP or WebSocket, while echoing to the local console.

## Quick Start

```ts
import { createLogger } from '@remote-logger/sdk';

const logger = createLogger({
  logId: 'your-log-file-id',
  apiKey: 'your-api-key',
});

logger.info("server started", { port: 3000 });
logger.warn("slow query", { duration: 1200, query: "SELECT ..." });
logger.error("payment failed", { orderId: "abc-123" });
```

## Configuration

```ts
const logger = createLogger({
  // Required
  logId: 'uuid',             // Log file ID from the dashboard
  apiKey: 'your-api-key',    // API key for ingestion auth

  // Optional
  group: 'api',              // Default group for all entries
  traceId: 'req-123',        // Default trace ID
  silent: false,             // Set true to suppress console output (default: false)
  level: 'DEBUG',            // Only send logs at this level and above (default: 'DEBUG')
  onError: (err, logs) => {  // Custom error handler for flush failures
    // handle error
  },
});
```

### `level` option

Controls which logs are sent to the remote service. Defaults to `'DEBUG'` (send everything). Logs below this level are silently dropped — they won't be sent remotely or printed to the console.

This is useful when you want full remote logging in production but don't need to send every debug log during local development where you're already watching the console:

```ts
const logger = createLogger({
  logId: 'your-log-file-id',
  apiKey: 'your-api-key',
  level: process.env.NODE_ENV === 'production' ? 'DEBUG' : 'ERROR',
});
```

In this setup, local dev only sends errors remotely (you're already seeing everything in your terminal), while production captures the full picture for dashboard viewing and LLM analysis.

### `silent` option

By default, every `logger.*` call also prints to the local console so developers don't lose visibility when replacing `console.log` with `logger.info`. Set `silent: true` in production to disable this.

## Log Methods

Every level supports two call styles:

### Simple form — message + optional metadata

```ts
logger.debug("cache miss", { key: "user:42" });
logger.info("request handled", { method: "GET", path: "/api/users", ms: 12 });
logger.warn("rate limit approaching", { current: 95, max: 100 });
logger.error("query failed", { table: "orders" });
logger.fatal("database unreachable");
```

The second argument is a plain metadata object. It can contain nested objects and arrays — the SDK sends it as-is.

### Object form — for per-call group or trace ID

```ts
logger.info({
  message: "user signed in",
  group: "auth",
  traceId: "req-abc",
  metadata: { userId: 123, method: "oauth" },
});
```

Use this when you need to override `group` or `traceId` on a single call without changing the logger's defaults.

## Error Logging

`error()` and `fatal()` accept Error objects directly — the SDK extracts the message, stack trace, and error type automatically:

```ts
try {
  await processPayment(order);
} catch (err) {
  logger.error(err as Error, { orderId: order.id });
}
```

This populates the `stack` and `error_type` columns in ClickHouse so stack traces and exception class names are stored as structured fields, not mashed into the message.

## Scoped Loggers

### Group Logger

```ts
const authLogger = logger.withGroup("auth");
authLogger.info("login attempt", { email: "user@example.com" });
// → group: "auth"
```

### Trace Logger

```ts
const reqLogger = logger.withTraceId("req-abc-123");
reqLogger.info("handling request");
reqLogger.warn("slow downstream call", { service: "billing", ms: 800 });
// → trace_id: "req-abc-123" on both entries
```

### Mutating defaults

```ts
// Set for all subsequent calls
logger.setGroup("worker");
logger.setTraceId("job-456");

// Clear
logger.setGroup(undefined);
logger.setTraceId(undefined);
```

## Console Interception

Capture existing `console.*` calls without changing application code:

```ts
logger.interceptConsole();       // uses group "console"
logger.interceptConsole("app");  // uses custom group

// Later, to restore original console behavior:
logger.restoreConsole();
```

This wraps `console.debug`, `console.log`, `console.info`, and `console.warn`. Errors are captured via `window.addEventListener('error')` and `unhandledrejection` listeners instead of wrapping `console.error`, to avoid polluting stack traces in frameworks like Next.js/React.

## Source Map Support (Vite)

Automatically resolve minified production stack traces back to original source. The Vite plugin uploads source maps at build time, and the ingestion service resolves stack traces before storing them.

```ts
// vite.config.ts
import remoteLoggerPlugin from '@remote-logger/sdk/vite';

export default defineConfig({
  plugins: [
    remoteLoggerPlugin({
      apiKey: process.env.REMOTE_LOGGER_API_KEY!,
      logFileId: 'your-log-file-id',
    }),
  ],
  build: { sourcemap: true },
});
```

The plugin:
- **Skips in dev mode** — stacks are already readable
- **Generates a release UUID** per build, injected as `__REMOTE_LOGGER_RELEASE__`
- **Uploads `.map` files** from the build output to the ingestion service on `closeBundle`
- **Multi-bundle (Electron):** All plugin instances in the same Node process share one release ID, so main + renderer maps are grouped under the same release

No SDK configuration needed — the SDK automatically detects `__REMOTE_LOGGER_RELEASE__` and attaches it to every log entry.

## AI Assistant Integration

Run the init command to configure your AI coding assistant (Claude Code, Cursor, etc.) to use the SDK:

```bash
npx @remote-logger/sdk init
```

This adds a reference to the SDK's workflow guide in your `CLAUDE.md` and `.cursorrules`. Once configured, your AI assistant will know how to place logs using the SDK and query them via MCP — no copy-pasting logs needed.

To set up manually, add this line to your `CLAUDE.md`:

```md
> See node_modules/@remote-logger/sdk/SKILL.md for the @remote-logger/sdk logging workflow.
```

## MCP Server (AI Log Analysis)

Remote Logger includes an MCP server that lets AI assistants query your logs directly.

### Add

```bash
claude mcp add remote-logger https://log.terodato.com/mcp --header "Authorization: Bearer YOUR_API_KEY"
```

### Remove

```bash
claude mcp remove remote-logger
```