react-fe-app-logger
v1.0.1
Published
A reusable FE logger package built with React + Vite.
Maintainers
Readme
app-logger-package
A robust and configurable TypeScript logger package for frontend applications, designed to intercept console messages (warn, error, info, debug) and send them to a specified API endpoint. It supports buffering logs and periodic flushing to optimize network requests.
Features
Console Interception: Overrides
console.warn,console.error,console.info, andconsole.debugto capture messages.Log Buffering: Collects logs in a buffer and sends them in batches to reduce network overhead.
Periodic Flushing: Automatically flushes remaining logs at a set interval.
Error Handling: Captures unhandled promise rejections and global window errors.
Configurable: Easily set API endpoint, environment, user details, buffer size, and flush interval.
TypeScript Support: Provides full type definitions for a seamless development experience.
Installation
To install the package in your frontend project, use npm or Yarn:
npm install react-fe-app-logger axios momentor
yarn add react-fe-app-logger axios momentNote: axios and moment are peer dependencies. Ensure they are installed in your project.
Usage
1. Initialize the Logger
Before using the logger, you must initialize it with your desired configuration. It's recommended to do this early in your application's lifecycle, for example, in your main.tsx or App.tsx file.
// src/main.tsx or src/App.tsx
import { initLogging, cleanupLogging } from 'react-fe-app-logger';
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
// --- Logger Configuration ---
const loggerConfig = {
logApiEndpoint: "https://your-api.com/logs", // REQUIRED: Your backend API endpoint for logs
environment: "production", // OPTIONAL: e.g., "development", "staging", "production"
userEmail: "[email protected]", // OPTIONAL: User's email for log context. Defaults to "Not_Authenticated_Logs".
tenantId: "YOUR_TENANT_ID", // OPTIONAL: Tenant ID for log context. Defaults to "DEFAULT".
bucketName: "your-s3-bucket-name", // REQUIRED: Relevant bucket name for log context.
maxBufferSize: 50, // OPTIONAL: Max number of logs to buffer before sending. Defaults to 20.
flushInterval: 30000 // OPTIONAL: Interval in ms to flush logs if buffer not full. Defaults to 10000 (10s).
};
// Initialize the logging service
initLogging(loggerConfig);
// Render your React application
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
// Optional: Clean up logging when the application unloads (e.g., user closes tab)
// This ensures any remaining logs in the buffer are sent.
window.addEventListener('beforeunload', cleanupLogging);- Using Console Methods Once initialized, the logger automatically intercepts console.warn, console.error, console.info, and console.debug. You can use them as you normally would, and the messages will be buffered and sent to your configured API endpoint.
// src/App.tsx (or any other component/file)
import React from 'react';
function MyComponent() {
const handleClick = () => {
console.info("Button clicked!");
console.warn("This is a warning from MyComponent.");
try {
throw new Error("Simulated error in MyComponent");
} catch (error) {
console.error("Caught an error:", error); // Error object will be serialized with stack trace
}
console.debug("Debugging data:", { data: "someValue", id: 123 });
};
const handleAsyncAction = async () => {
try {
const response = await fetch('https://non-existent-api.com/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.info("Data fetched:", data);
} catch (error) {
// This will be caught by console.error and potentially unhandledrejection listener
console.error("Failed to fetch data:", error);
}
};
// Simulate an unhandled promise rejection
const simulateUnhandledRejection = () => {
Promise.reject("This is an unhandled promise rejection!");
};
// Simulate a global error
const simulateGlobalError = () => {
// @ts-ignore
nonExistentFunction(); // This will cause a global error
};
return (
<div>
<h2>Logger Demo</h2>
<button onClick={handleClick}>Log Messages</button>
<button onClick={handleAsyncAction}>Fetch Data (Simulated)</button>
<button onClick={simulateUnhandledRejection}>Simulate Unhandled Rejection</button>
<button onClick={simulateGlobalError}>Simulate Global Error</button>
<p>Open your browser's developer console and network tab to see logs.</p>
</div>
);
}
export default MyComponent;3. Cleaning Up
The cleanupLogging function should be called when your application is about to unload (e.g., when the user closes the browser tab or navigates away). This ensures that any logs remaining in the buffer are sent before the page closes.
// Example from main.tsx above
window.addEventListener('beforeunload', cleanupLogging);Configuration Options
Here's a detailed explanation of the LoggingConfig parameters:
- logApiEndpoint: string (Required)
The URL of your backend API endpoint where logs will be sent. This API should be set up to receive POST requests with a JSON body containing the log data.
- environment: string (Required)
A string indicating the environment where the application is running (e.g., "development", "staging", "production", "test"). This helps categorize logs on your backend.
- userEmail?: string (Optional)
The email address of the currently authenticated user. This will be included in each log entry for better user-specific debugging. If not provided, it defaults to "Not_Authenticated_Logs".
- tenantId?: string (Optional)
An identifier for the tenant or account the user belongs to. Useful in multi-tenant applications for filtering logs. If not provided, it defaults to "DEFAULT".
- bucketName?: string (Required)
A specific bucket name related to the context of the logs, if applicable to your application's architecture (e.g., S3 bucket name). If not provided, it defaults to undefined.
- maxBufferSize?: number (Optional)
The maximum number of log entries to store in the buffer before automatically sending them to the server. Defaults to 20.
flushInterval?: number (Optional)
The interval in milliseconds at which the logger will periodically send any accumulated logs in the buffer, even if maxBufferSize has not been reached. This prevents logs from being stuck in the buffer indefinitely. Defaults to 10000 (10 seconds).
Log Payload Structure Logs are sent to your logApiEndpoint as a POST request with a JSON body similar to this:
{
"logs": [
{
"timestamp": "YYYY-MM-DDTHH:mm:ss.SSSZ",
"level": "INFO" | "WARN" | "ERROR" | "DEBUG",
"message": "Your log message here",
"userAgent": "Mozilla/...",
"url": "http://your-app.com/page",
"user": "[email protected]",
"tenantId": "YOUR_TENANT_ID",
"environment": "production",
"stackTrace": "Error stack trace (if level is ERROR)",
"bucketName": "your-s3-bucket-name"
},
// ... more log entries
],
"env": "production",
"user": "[email protected]",
"tenantId": "YOUR_TENANT_ID",
"module": "DocGenAI",
"bucketName": "your-s3-bucket-name"
}Development and Publishing For information on how this package is built and published using Vite and TypeScript, refer to the project's vite.config.ts and package.json files.
