Send from Node.js
A small Node.js function that sends a log to OpenLogger and reports errors.
This recipe sends logs from a Node.js app with the built-in fetch. It needs no extra package. It turns data into a JSON string for you.
The code
Save it as send.mjs:
// send.mjs: sends logs to OpenLogger.
const OPENLOGGER = process.env.OPENLOGGER_URL;
const TOKEN = process.env.OPENLOGGER_TOKEN;
async function log(entry) {
const body = { app: 'Demo project', ...entry };
if (body.data && typeof body.data !== 'string')
body.data = JSON.stringify(body.data);
const response = await fetch(OPENLOGGER + '/', {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-token': TOKEN },
body: JSON.stringify(body),
signal: AbortSignal.timeout(10000)
});
const text = await response.text();
if (!response.ok)
throw new Error(response.status + ' ' + text.substring(0, 200));
return JSON.parse(text);
}
console.log(await log({ type: 'error', message: 'Payment failed', userid: 'u100', username: 'Jane Doe', data: { order: 1003, reason: 'card declined' } }));
try {
await log({ app: '', message: 'No app name' });
} catch (e) {
console.log(e.message);
}Run it
OPENLOGGER_URL=https://logs.example.com OPENLOGGER_TOKEN=YOUR_TOKEN node send.mjsThe output:
{ success: true }
400 [{"name":"app","error":"The field \"app\" is invalid","path":"app","prefix":"app"}]The first log is stored with its data; the second call fails because app is empty.
Notes
- The body is read as text first, because a wrong token answers
401with an HTML page. See Errors. - The timeout stops the request after 10 seconds, so a slow log server does not hold up your app.
- Keep the token on the server. Never put it in code that runs in the browser.