generated from nhcarrigan/template
66413c5e21
Wrap all async API route handlers and services in try/catch blocks, piping errors to the @nhcarrigan/logger telemetry service. Add a frontend logError utility, React ErrorBoundary, and overridden console to forward all unhandled client-side errors to the backend telemetry endpoint.
69 lines
2.3 KiB
TypeScript
69 lines
2.3 KiB
TypeScript
/**
|
|
* @file Frontend logger that forwards console output to the backend telemetry service.
|
|
* @copyright nhcarrigan
|
|
* @license Naomi's Public License
|
|
* @author Naomi Carrigan
|
|
*/
|
|
/* eslint-disable no-console -- This file intentionally overrides console methods */
|
|
|
|
type Level = "debug" | "info" | "warn";
|
|
|
|
const post = (path: string, body: object): void => {
|
|
void fetch(path, {
|
|
body: JSON.stringify(body),
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention -- HTTP header names use kebab-case
|
|
headers: { "Content-Type": "application/json" },
|
|
method: "POST",
|
|
}).catch(() => {
|
|
// Intentionally swallowed — we cannot log logger failures without infinite recursion.
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Overrides the global console.log and console.error methods so that all
|
|
* frontend log output is forwarded to the backend telemetry endpoints.
|
|
* Must be called once at application startup before any other code runs.
|
|
*/
|
|
const initialiseFrontendLogger = (): void => {
|
|
const originalLog = console.log.bind(console);
|
|
const originalError = console.error.bind(console);
|
|
|
|
console.log = (...consoleArguments: Array<unknown>): void => {
|
|
originalLog(...consoleArguments);
|
|
const level: Level = "info";
|
|
const message = consoleArguments.map((argument) => {
|
|
return typeof argument === "string"
|
|
? argument
|
|
: JSON.stringify(argument);
|
|
}).join(" ");
|
|
post("/api/fe/log", { level, message });
|
|
};
|
|
|
|
console.error = (...consoleArguments: Array<unknown>): void => {
|
|
originalError(...consoleArguments);
|
|
const message = consoleArguments.map((argument) => {
|
|
if (argument instanceof Error) {
|
|
return `${argument.message}\n${argument.stack ?? ""}`;
|
|
}
|
|
return typeof argument === "string"
|
|
? argument
|
|
: JSON.stringify(argument);
|
|
}).join(" ");
|
|
const context = "console.error";
|
|
post("/api/fe/error", { context, message });
|
|
};
|
|
|
|
console.warn = (...consoleArguments: Array<unknown>): void => {
|
|
originalLog(...consoleArguments);
|
|
const level: Level = "warn";
|
|
const message = consoleArguments.map((argument) => {
|
|
return typeof argument === "string"
|
|
? argument
|
|
: JSON.stringify(argument);
|
|
}).join(" ");
|
|
post("/api/fe/log", { level, message });
|
|
};
|
|
};
|
|
|
|
export { initialiseFrontendLogger };
|