Const
{
level: "info",
timestamp: true,
prefix: "",
group: false,
groupCollapsed: false,
stackTrace: false
}
Internal storage for all log entries.
[]
Maximum number of log entries to store before removing oldest entries.
1000
Logs a debug message with optional metadata.
The debug message to log
Optional configuration for the log entry
// Simple debug message
LoggingUtils.debug("Processing started");
// Debug with data and prefix
LoggingUtils.debug("Data processed", {
prefix: "DataService",
data: { count: 100, status: "success" }
});
// Debug with grouping
LoggingUtils.debug("Complex operation", {
group: true,
groupCollapsed: true,
data: { steps: ["step1", "step2"] }
});
Logs an error message with optional stack trace and metadata.
The error message to log
Optional configuration for the log entry
try {
// ... some code that might throw
} catch (error) {
LoggingUtils.error("Failed to process data", {
data: error,
prefix: "DataService",
stackTrace: true
});
}
// Error with custom data
LoggingUtils.error("API request failed", {
data: {
status: 500,
endpoint: "/api/data",
response: "Internal Server Error"
}
});
Exports all stored log entries as a formatted JSON string.
A JSON string containing all log entries
// Export logs to file
const logs = LoggingUtils.exportLogEntries();
const blob = new Blob([logs], { type: 'application/json' });
const url = URL.createObjectURL(blob);
// Export logs to server
const logs = LoggingUtils.exportLogEntries();
await fetch('/api/logs', {
method: 'POST',
body: logs,
headers: { 'Content-Type': 'application/json' }
});
Formats a number of bytes into a human-readable string with appropriate unit.
The number of bytes to format
A formatted string with appropriate unit (B, KB, MB, GB, TB)
const size = LoggingUtils.formatBytes(1024 * 1024);
console.log(size); // "1.00 MB"
const smallSize = LoggingUtils.formatBytes(500);
console.log(smallSize); // "500.00 B"
const largeSize = LoggingUtils.formatBytes(1024 * 1024 * 1024 * 2);
console.log(largeSize); // "2.00 GB"
Gets a copy of all stored log entries.
An array of log entries
// Get all logs
const allLogs = LoggingUtils.getLogEntries();
console.log(`Total logs: ${allLogs.length}`);
// Filter logs in memory
const errorLogs = LoggingUtils.getLogEntries()
.filter(log => log.level === 'error');
Gets log entries filtered by a specific log level.
The log level to filter by
An array of filtered log entries
// Get all error logs
const errorLogs = LoggingUtils.getLogEntriesByLevel("error");
console.log(`Error count: ${errorLogs.length}`);
// Get all debug logs
const debugLogs = LoggingUtils.getLogEntriesByLevel("debug");
console.log(`Debug count: ${debugLogs.length}`);
Gets log entries within a specific time range.
The start time of the range
The end time of the range
An array of filtered log entries
// Get logs from today
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const todayLogs = LoggingUtils.getLogEntriesByTimeRange(yesterday, today);
console.log(`Logs in last 24 hours: ${todayLogs.length}`);
// Get logs from specific time period
const startDate = new Date("2024-01-01");
const endDate = new Date("2024-01-02");
const periodLogs = LoggingUtils.getLogEntriesByTimeRange(startDate, endDate);
Logs an informational message with optional metadata.
The info message to log
Optional configuration for the log entry
// Simple info message
LoggingUtils.info("Application started");
// Info with data and prefix
LoggingUtils.info("User logged in", {
prefix: "Auth",
data: { userId: "123", role: "admin" }
});
// Info with grouping
LoggingUtils.info("Configuration loaded", {
group: true,
data: { settings: { theme: "dark", language: "en" } }
});
Imports log entries from a JSON string.
The JSON string containing log entries
If the JSON string is invalid or cannot be parsed
// Import logs from file
const json = await fetch('/logs.json').then(r => r.text());
LoggingUtils.importLogEntries(json);
// Import logs from server
const response = await fetch('/api/logs');
const json = await response.text();
LoggingUtils.importLogEntries(json);
Logs a message with the specified options.
The message to log
Configuration options for the log entry
// Custom log with all options
LoggingUtils.log("Custom message", {
level: "info",
prefix: "Custom",
group: true,
groupCollapsed: true,
stackTrace: true,
data: { custom: "data" }
});
// Simple log with default options
LoggingUtils.log("Simple message");
Logs memory usage information if available in the browser.
The label for the memory measurement
// Log memory usage
LoggingUtils.measureMemory("After data load");
// Output: Memory: After data load { used: "50.2 MB", total: "100.0 MB", limit: "500.0 MB" }
// Track memory usage over time
setInterval(() => {
LoggingUtils.measureMemory("Periodic check");
}, 60000);
Creates a performance measurement for synchronous operations.
The label for the performance measurement
A function to end the measurement and log the duration
// Measure a synchronous operation
const endMeasurement = LoggingUtils.measurePerformance("Data processing");
// ... do some work ...
endMeasurement();
// Output: Performance: Data processing { duration: "123.45ms" }
// Measure multiple operations
const endTotal = LoggingUtils.measurePerformance("Total processing");
const endStep1 = LoggingUtils.measurePerformance("Step 1");
// ... do step 1 ...
endStep1();
const endStep2 = LoggingUtils.measurePerformance("Step 2");
// ... do step 2 ...
endStep2();
endTotal();
Measures the performance of an asynchronous function.
A Promise with the function result
// Measure an API call
const result = await LoggingUtils.measureAsyncPerformance(
"API call",
async () => await fetchData()
);
// Measure multiple async operations
const results = await Promise.all([
LoggingUtils.measureAsyncPerformance("API 1", () => fetchData1()),
LoggingUtils.measureAsyncPerformance("API 2", () => fetchData2())
]);
Logs a warning message with optional metadata.
The warning message to log
Optional configuration for the log entry
// Simple warning
LoggingUtils.warn("Resource usage high");
// Warning with data and prefix
LoggingUtils.warn("High memory usage", {
prefix: "System",
data: { cpu: "80%", memory: "75%" }
});
// Warning with grouping
LoggingUtils.warn("Multiple issues detected", {
group: true,
data: { issues: ["CPU", "Memory", "Disk"] }
});
Default configuration options for logging.