@moonwatch/js
v0.1.16
Published
JavaScript SDK for Moonwatch
Maintainers
Readme
Moonwatch SDK
A lightweight logging SDK that sends structured logs to a Moonwatch backend via HTTP or WebSocket, while echoing to the local console.
Quick Start
import { createLogger } from '@moonwatch/js';
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
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:
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
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
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:
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
const authLogger = logger.withGroup("auth");
authLogger.info("login attempt", { email: "[email protected]" });
// → group: "auth"Trace Logger
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 entriesMutating defaults
// Set for all subsequent calls
logger.setGroup("worker");
logger.setTraceId("job-456");
// Clear
logger.setGroup(undefined);
logger.setTraceId(undefined);Dynamic Trace ID Provider
For server-side applications handling concurrent requests, use setTraceIdProvider to dynamically resolve the trace ID per log entry. This works with Node.js AsyncLocalStorage to associate every log (including intercepted console.log calls) with the request that triggered it:
import { AsyncLocalStorage } from "node:async_hooks";
import { randomUUID } from "node:crypto";
import { createLogger } from "@moonwatch/js";
const traceStorage = new AsyncLocalStorage<string>();
const logger = createLogger({
logId: "your-log-file-id",
apiKey: "your-api-key",
silent: true,
});
// Register the provider — called on every log to resolve the current trace ID
logger.setTraceIdProvider(() => traceStorage.getStore());
logger.interceptConsole();
// In your HTTP middleware:
app.use(async (ctx, next) => {
const traceId = randomUUID();
await traceStorage.run(traceId, next);
});
// Now any console.log during a request automatically gets that request's trace ID
console.log("processing order"); // → trace_id: "the-request-uuid"The provider is checked on every log call with the following priority:
- Per-call
traceId(via object form orScopedLogger) traceIdProvider()return value- Static
traceIdfrom config /setTraceId()
Console Interception
Capture existing console.* calls without changing application code:
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.
// vite.config.ts
import moonwatchPlugin from '@moonwatch/js/vite';
export default defineConfig({
plugins: [
moonwatchPlugin({
apiKey: process.env.MOONWATCH_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
__MOONWATCH_RELEASE__ - Uploads
.mapfiles from the build output to the ingestion service oncloseBundle - 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 __MOONWATCH_RELEASE__ and attaches it to every log entry.
MCP Server (AI Log Analysis)
Moonwatch includes an MCP server that lets AI assistants query your logs directly.
Add
claude mcp add --transport http moonwatch https://mcp.moonwatch.dev/mcp --header "Authorization: Bearer YOUR_API_KEY"Remove
claude mcp remove moonwatchNote: The
--transport httpflag is required — without it,claudedefaults to stdio transport which won't work with a remote server.
