JavaScript
Structured logs from a website or a Node service. TypeScript, ESM, no dependencies.
One package, @lyrelog/js, for browsers and Node 22.12 or later. The same import works
everywhere: bundlers pick the browser build, Node picks the Node build. The package is ESM only:
import it, or require() it (Node 22.12 loads ES modules without a flag).
Internal preview: this package isn't published yet. Until it is, pnpm add @lyrelog/js fails:
there is no package on npm.
Install
pnpm add @lyrelog/jsStart
Lyrelog.init returns a client. Make one per page load or per process, as early as possible.
import { Lyrelog } from "@lyrelog/js";
export const log = Lyrelog.init({
apiKey: "lyr_ing_...", // ingest-only: it can append events, never read them
release: "2.0.1",
});In the browser, use the project's ingest key, lyr_ing_...: it can only append events, so it is
safe in a page. On Node, use a server key, lyr_srv_...: its events are
verified and one address has no daily share of the month. Never
put a server key in browser code. To get verified events from a page, send them
through your own server.
Events go to https://ingest.lyrelog.com. Pass endpoint only to send them somewhere else. It's
the base URL; a pasted .../v1/events:batch path is stripped.
Calling init again with the same endpoint and key gives back the live client when the config is
the same, and otherwise closes it and starts a new one, so a hot reload never leaves two clients.
Without an apiKey, or with an endpoint that isn't https (plain http only on localhost), the
client warns once in the console and sends nothing.
Content Security Policy
If your site sets a Content Security Policy, allow the ingest in connect-src:
Content-Security-Policy: connect-src 'self' https://ingest.lyrelog.comLog events
One method per level: trace, debug, info, notice, warning, error, critical, or
log(level, message, options).
log.info("checkout_done", { category: "checkout", attrs: { items: 3, total_cents: 4200 } });
log.error("job_failed", { attrs: { job: "digest" }, payload: { response: raw } });A log call fits the event to the server's limits, serializes it (later changes to your objects
don't leak in) and queues it. Bad input is turned into something valid, never an exception.
After close(), log calls do nothing.
Loggers for each area
const jobs = log.logger("jobs");
jobs.info("job_done", { attrs: { job: "digest", ms: 412 } });A logger has every level method and log. To capture an error in its area, use
log.captureException(error, { category: "jobs" }).
Users
log.setUser(accountId); // attached to every following event
log.setUser(null); // on sign-outlog.sessionId gives the current session, for example for a support screen. The user id isn't
saved: in the browser, call setUser again on each page load once you know who the person is.
Screens
log.screen("Checkout");Logs screen_viewed in the navigation area with the screen before and the seconds spent on it,
and every following event carries screen. On the web, call it when the page changes. Name the
screen rather than passing the URL: /orders/1234 would make one screen per order.
function OrderPage() {
useEffect(() => log.screen("Order"), []);
// ...
}Requests
There is no automatic request logging. Log the requests you care about with a stable name and the fields you want to chart, as the Swift SDK does:
const started = performance.now();
const res = await fetch("/api/cart");
log.log(res.ok ? "debug" : "warning", res.ok ? "http_request" : "http_request_failed", {
category: "network",
attrs: { method: "GET", path: "/api/cart", status: res.status, duration_ms: Math.round(performance.now() - started) },
});Exceptions
try {
await pay();
} catch (error) {
log.captureException(error, { category: "checkout", attrs: { step: "pay" } });
}Records exception (level error, or level if you pass one) with error_type and
error_message as attributes, and the name, message, stack, code and up to three causes in
the payload. Anything thrown works, not only Error. From a thrown value that isn't an Error,
only its name, message, code and status are kept, never the rest of the object (an HTTP
client's error would carry its request headers). In the browser, URLs in stacks lose their query
string and fragment.
Uncaught errors
They are captured for you, as the same exception event with handled: false and a
mechanism:
- In the browser, errors that reach
window(onerror) and promises rejected with no handler (onunhandledrejection). The console still shows them. The opaque cross-origin "Script error." carries nothing useful and is skipped. - On Node, an uncaught exception or rejection. Lyrelog only watches (it uses
uncaughtExceptionMonitor), so the process still crashes as it would without it. There's no time to send before it exits, so the event is written to a small file in the temp folder and sent the next time the app starts with the same key.
At most 10 a minute are captured, and the same error once every 10 seconds, so a loop that
throws can't flood your project; stats().skippedErrors counts what was skipped. Turn it all off
with captureErrors: false.
Errors your framework catches
Errors a framework catches itself never become uncaught: call captureException there. In
React, from an error boundary:
import { Component, type ErrorInfo, type ReactNode } from "react";
class ErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
componentDidCatch(error: unknown, info: ErrorInfo) {
log.captureException(error, { category: "ui", attrs: { component_stack: info.componentStack ?? "" } });
}
render() {
return this.state.failed ? <p>Something went wrong.</p> : this.props.children;
}
}In Express, from an error handler, added after your routes:
app.use((err: unknown, req: Request, res: Response, next: NextFunction) => {
log.captureException(err, {
category: "http",
attrs: { method: req.method, route: req.route?.path ?? "unmatched" },
});
next(err);
});Environments and platform
- Node:
environmentisproductiononly whenNODE_ENV=production. Anything else, including noNODE_ENVat all, isdevelopment: setNODE_ENV=production(orenvironment) on your servers.platformisnode. - Browser:
environmentisdevelopmentonlocalhost,127.0.0.1,[::1]or a.localhosthost, elseproduction.platformisweb.
Set either in init, for example Lyrelog.init({ apiKey, environment: "staging" }).
Any name works: lowercase letters, digits, - and _, up to 32.
Consent
const log = Lyrelog.init({ apiKey, consent: "pending" });
// later
log.setConsent("granted"); // or "denied"pending keeps events in memory unsent, granted sends them, denied drops everything (and, on
Node, the file of uncaught errors waiting to be sent).
Consent isn't saved between page loads: store the person's choice yourself and pass it to init.
In the browser, until consent is granted the install and session ids stay in memory, not in
localStorage or sessionStorage.
Redacting and filtering
A value becomes "[redacted]", in attributes, the payload and anything turned into a string, when
its key name, lowercased and without -, _, . or spaces, is or ends with one of
authorization, cookie, password, passwd, secret, token, apikey, privatekey,
credential, credentials, accesskey or signature. So X-Api-Key, csrf_token,
Set-Cookie and user_token are redacted; token_count and max_tokens aren't. redactKeys
replaces this list with your own names, matched the same way; an empty list turns redaction off.
To add to the defaults, spread DEFAULT_REDACT_KEYS, which the package exports.
To change or drop events yourself, pass beforeSend. It gets each event after redaction and
before it's queued, and returns it, changed or not, or null to drop it. The ids, ts and
resource can't be changed, what you return is fitted to the limits again, and a hook that throws
drops the event.
import { Lyrelog, DEFAULT_REDACT_KEYS } from "@lyrelog/js";
const log = Lyrelog.init({
apiKey: "lyr_ing_...",
redactKeys: [...DEFAULT_REDACT_KEYS, "card_number"],
beforeSend(event) {
if (event.message === "health_check") return null;
if (event.attrs?.email) event.attrs.email = "[redacted]";
return event;
},
});Flush and stop
In the browser you rarely need either: the timer and hiding the page already send.
await log.flush(); // send what is queued nowOn Node, close the client in your shutdown path, so what is queued goes out before the process exits:
process.on("SIGTERM", async () => {
await log.close(); // sends what is queued, then stops
process.exit(0);
});A script that ends with process.exit() skips beforeExit and loses what is still queued:
await log.close() first, as above.
In a serverless function (AWS Lambda, Vercel and Netlify functions, Cloudflare Workers), the runtime freezes or ends the function as soon as it answers, before the timer fires. Flush before returning:
export async function handler(event) {
log.info("order_created", { attrs: { order_id: event.id } });
await log.flush();
return { statusCode: 200 };
}flush, close and the send on page hide all respect a Retry-After the server asked for:
inside one, flush returns at once and the events wait.
log.stats() returns { queued, queuedBytes, dropped, delivered, rejected, skippedErrors, disabled };
disabled is true after a 401 or 403, or when the client has no key or endpoint to send to.
In development and tests
Leave apiKey empty and the client warns once and sends nothing, or pass consent: "denied" to
drop every event without a warning:
const log = Lyrelog.init({
apiKey: process.env.LYRELOG_KEY ?? "",
consent: process.env.NODE_ENV === "test" ? "denied" : "granted",
});Verified events
A verified event is one that can't have been sent by someone who copied the public ingest key out of an app or a web page. What that proves, and what it doesn't, is on Verified events.
On Node, send with a server key, lyr_srv_.... Every event it sends is verified (verified_by
is server) and doesn't count toward the
daily share of one address. An owner
makes it on the project's API keys page, Send events from a server, after a recent sign-in
(within 10 minutes), and it is shown once. It is a secret: keep it out of the repository and read
it from the server's environment or secret store.
export const log = Lyrelog.init({
apiKey: process.env.LYRELOG_KEY!, // lyr_srv_..., set in the server's environment
});In a browser the key is the public ingest key, so a page's events arrive unverified, and they
count toward the daily share. Never put a server key in browser code: anything in the page can
be read. To verify a site's events, relay them
through your own server: point
endpoint at a route on your backend that forwards each batch with the server key. That route
must accept events only from your own signed-in sessions, or it verifies nothing.
To check, open the explorer: in Filter, pick Verified by and Server key (the other values are App Attest and Not verified). An opened event says it under Context, in its Sender line: Verified, server key, or Not verified, public key.
Events sent with an ingest key or a full-access key, lyr_adm_..., arrive unverified: anyone
holding a public key could have sent the same. A verified event proves who sent it, not that
what it says is true.
See Verified events for who verifies what and the daily share.
Configuration
| Option | Default | Meaning |
|---|---|---|
endpoint | https://ingest.lyrelog.com | The base URL; a pasted /v1/... path is stripped. https only, http only on localhost |
apiKey | required | Browser: the project's ingest key, safe in client code. Node: a server key, never in client code. Without it the client sends nothing |
environment | detected | Any name: lowercase letters, digits, - and _, up to 32 |
platform | web / node | api, worker... |
release | Node: npm_package_version | Sent as app_version. The default exists only when started through a package script: pass it yourself under node server.js, Docker or systemd |
appId | Web: the host name. Node: npm_package_name | Sent as app_id. On Node, the same caveat as release |
minimumLevel | debug | Events below it are dropped before queueing |
flushIntervalMs | 5000 | How often the queue is sent |
maxQueue | 10000 | Events waiting in memory; beyond it the oldest go |
maxQueueBytes | 16 MiB | The same cap, in bytes |
redactKeys | DEFAULT_REDACT_KEYS | Key names to redact; replaces the defaults, [] turns it off |
beforeSend | none | Change an event, or return null to drop it |
consent | granted | granted, pending or denied |
captureErrors | true | Capture uncaught errors and unhandled rejections |
Delivery and limits
| When it sends | Every 5 s, as soon as 500 events wait, on flush() and close(). In the browser also when the page hides; on Node on beforeExit (not on process.exit(); the timer never keeps the process alive). |
| Batches | Up to 500 events or 512 KiB, NDJSON, gzip (CompressionStream in browsers, zlib on Node). An event over 1 MiB is dropped and counted. |
| Retries | Backoff with full jitter (1 s doubling to 5 min), honoring Retry-After. A retry resends the same events with the same ids. Any other 4xx drops the batch; a 3xx drops it with a warning (redirects aren't followed); a refused key stops sending until restart and keeps the events. |
| Monthly quota | When a Free organization has used its month's events, the server answers 429. The events stay in the queue and go out once the server takes them again, up to maxQueue. The client logs one console.warn with the server's message, and again only after a batch has been accepted in between. |
| Its own problems | A wrong endpoint, a redirect or a dropped batch: one console.warn starting with [lyrelog]. A refused key and rejected lines: console.debug, so turn on verbose messages in the browser's console to see them. |
| Context | Web: os_name: "web", the browser family as device_model, navigator.language as locale, an install id in localStorage and a session id in sessionStorage (new after 30 min idle). Node: process.platform, os.release(), the CPU architecture, and ids per process. Storage that throws (private mode) falls back to memory. |
| Limits | Fitted before queueing; extra attributes are counted in lyrelog_dropped_attrs, dots in attribute names become _, a payload over 64 KiB becomes a summary with a preview. |
Worth knowing:
- The queue lives in memory. Events still waiting when a tab closes for good, or a process
is killed with
SIGKILLor ends withprocess.exit(), are lost. Callclose()in your server's shutdown path, andflush()at the end of a serverless handler. - A hiding page sends at most about 60 KB, the rest waits for the page to come back.
- The ingest key is public on the web. Anyone who reads your page can send events to the project too, so don't treat incoming events as trusted input. Those events aren't verified; events from Node with a server key are.