### Install electron-log with npm Source: https://github.com/megahertz/electron-log/blob/master/README.md Install the electron-log package using npm. This command is for Node.js environments. ```bash npm install electron-log ``` -------------------------------- ### GitHub Issue Example Source: https://github.com/megahertz/electron-log/blob/master/docs/errors.md An example demonstrating how to use the `onError` callback to create a GitHub issue for errors occurring in the main process. ```APIDOC ```js log.errorHandler.startCatching({ showDialog: false, onError({ createIssue, error, processType, versions }) { if (processType === 'renderer') { return; } electron.dialog.showMessageBox({ title: 'An error occurred', message: error.message, detail: error.stack, type: 'error', buttons: ['Ignore', 'Report', 'Exit'], }) .then((result) => { if (result.response === 1) { createIssue('https://github.com/my-acc/my-app/issues/new', { title: `Error report for ${versions.app}`, body: 'Error:\n```' + error.stack + '\n```\n' + `OS: ${versions.os}` }); return; } if (result.response === 2) { electron.app.quit(); } }); } }); ``` ``` -------------------------------- ### Log from First Renderer Process Source: https://github.com/megahertz/electron-log/blob/master/e2e/multiple-renderers/index.html Logs a warning message from the initial renderer process using `__electronLog.warn`. This is useful for initial setup or debugging. ```javascript __electronLog.warn('log from the first renderer process'); ``` -------------------------------- ### Start Logging Events Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md Initiates the logging of specified electron events. Options can be provided to customize which events are logged. ```APIDOC ## log.eventLogger.startLogging(options?) ### Description Start saving event logs. ### Method `log.eventLogger.startLogging(options?)` ``` -------------------------------- ### log.initialize() - Renderer IPC Bridge Setup Source: https://context7.com/megahertz/electron-log/llms.txt Injects the built-in preload script into Electron sessions for renderer logging. Must be called in the main process before any BrowserWindow is created. Options allow customization of session injection, future sessions, and spying on console logs. ```javascript // main.js import log from 'electron-log/main'; import { session } from 'electron'; // Default: inject into the default session and all future sessions log.initialize(); // Custom session only log.initialize({ getSessions: () => [session.fromPartition('persist:myapp')] }); // Disable injection into future sessions log.initialize({ includeFutureSessions: false }); // Spy on console.log calls in every renderer (objects are serialized as strings) log.initialize({ spyRendererConsole: true }); // Using raw IPC from a preload script (when log.initialize() is not used) import { ipcRenderer } from 'electron'; pcRenderer.send('__ELECTRON_LOG__', { data: ['Direct IPC log'], level: 'info', variables: { processType: 'renderer' }, }); ``` -------------------------------- ### Example HTTP POST Request Body Source: https://github.com/megahertz/electron-log/blob/master/docs/transports/remote.md This is an example of the JSON payload sent by the remote transport for a warning message. It includes client information, log data, timestamp, level, and process type. ```http POST /myapp/add-log HTTP/1.1 Content-Length: 300 Content-Type: application/json Host: example.com Connection: close { "client": { "name": "electron-application" }, "data": [ "Some problem appears", { "error": { "constructor": "Error", "stack": "Error: test\n at App.createWindow ..." } } ], "date": 1574238042989, "level": "warn", "variables": { "processType": "browser" } } ``` -------------------------------- ### Start Catching Errors with Custom Handler Source: https://github.com/megahertz/electron-log/blob/master/docs/errors.md Initializes error catching in electron-log with a custom handler. This example disables the default dialog and implements logic to show a custom message box, with options to ignore, report (create a GitHub issue), or exit the application. The custom handler is only active for the main process. ```javascript log.errorHandler.startCatching({ showDialog: false, onError({ createIssue, error, processType, versions }) { if (processType === 'renderer') { return; } electron.dialog.showMessageBox({ title: 'An error occurred', message: error.message, detail: error.stack, type: 'error', buttons: ['Ignore', 'Report', 'Exit'], }) .then((result) => { if (result.response === 1) { createIssue('https://github.com/my-acc/my-app/issues/new', { title: `Error report for ${versions.app}`, body: 'Error:\n```' + error.stack + '\n```\n' + `OS: ${versions.os}` }); return; } if (result.response === 2) { electron.app.quit(); } }); } }); ``` -------------------------------- ### Using Electron's App Path for Logs Source: https://github.com/megahertz/electron-log/blob/master/docs/transports/file.md This example shows how to override the default path resolution to use Electron's `app.getPath('logs')` method. This is useful if you prefer to use the standard Electron log directory. ```javascript log.transports.file.resolvePathFn = (variables) => { return path.join(variables.electronDefaultDir, variables.fileName); } ``` -------------------------------- ### Formatter for Specific Events Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md Provides an example of creating a specific formatter for a 'console-message' event within WebContents. ```APIDOC ## log.eventLogger.formatters.webContents['console-message'] ### Description A set of functions which formats a specific event. ### Code Example ```js log.eventLogger.formatters.webContents['console-message'] = ({ args: [level, message, line, sourceId], event, eventName, eventSource }) => { const webContents = event.sender; if (level > 2) { return undefined; } return { message, source: `${sourceId}:${line}`, url: webContents?.getURL() }; }; ``` ``` -------------------------------- ### Configure Log Format Templates Source: https://context7.com/megahertz/electron-log/llms.txt Customize the output format for transports using string templates and available tokens. This example shows setting a full date-time format for the file transport and an ISO timestamp format for the console transport. ```javascript import log from 'electron-log/main'; // Full date-time template with scope and custom variable log.variables.env = 'prod'; log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] [{scope}] [{env}] {text}'; // → [2024-06-01 09:15:30.042] [info] [auth] [prod] User logged in // ISO timestamp template log.transports.console.format = '[{iso}] [{level}] {text}'; // → [2024-06-01T09:15:30.042Z] [info] User logged in // Available tokens: // {y} year {m} month {d} day // {h} hour {i} minute {s} second {ms} millisecond // {z} tz offset {iso} toISOString {level} log level {text} message // {scope} scope label {logId} logger id {processType} browser|renderer // + any key added to log.variables ``` -------------------------------- ### Format templates — reference Source: https://context7.com/megahertz/electron-log/llms.txt Provides a reference for available tokens and examples for customizing log message formats across different transports. ```APIDOC ## Format templates — reference All built-in token names usable in string format templates. ```js import log from 'electron-log/main'; // Full date-time template with scope and custom variable log.variables.env = 'prod'; log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] [{scope}] [{env}] {text}'; // → [2024-06-01 09:15:30.042] [info] [auth] [prod] User logged in // ISO timestamp template log.transports.console.format = '[{iso}] [{level}] {text}'; // → [2024-06-01T09:15:30.042Z] [info] User logged in // Available tokens: // {y} year {m} month {d} day // {h} hour {i} minute {s} second {ms} millisecond // {z} tz offset {iso} toISOString {level} log level {text} message // {scope} scope label {logId} logger id {processType} browser|renderer // + any key added to log.variables ``` ``` -------------------------------- ### Start Catching Errors Source: https://github.com/megahertz/electron-log/blob/master/docs/errors.md Initializes the error catching mechanism in electron-log. This should be called in both main and renderer processes if you need to collect logs from both. ```APIDOC ## log.errorHandler.startCatching(options?) ### Description Start catching unhandled errors and rejections. ### Method `log.errorHandler.startCatching` ### Parameters #### Options - **showDialog** (boolean) - Optional - Default: `true`. Controls whether an error dialog is shown. It follows Electron's logic, typically only showing in the main process. Setting to `false` disables the dialog for all errors. - **onError** ({ createIssue, error, processType, versions }) => void | false - Optional - Default: `null`. A callback function to handle errors. If it returns `false`, the error will not be processed further. In a renderer process, only the `error` property is available. The `createIssue` function can be used to open a GitHub issue URL with appended query parameters. `processType` indicates if the error occurred in the 'browser' (main) or 'renderer' process. `versions` provides application, Electron, and OS version information. ``` -------------------------------- ### Start logging Electron events Source: https://github.com/megahertz/electron-log/blob/master/README.md Configure electron-log to capture and save critical Electron events to the log file. This is useful for diagnosing issues related to application lifecycle and process management. ```javascript log.eventLogger.startLogging(options?); ``` -------------------------------- ### Read and Clear Log Files Source: https://context7.com/megahertz/electron-log/llms.txt Access the current log file instance to get its path and size, read all log content, and clear the log file. ```javascript // Get current log file instance const logFile = log.transports.file.getFile(); console.log('Log path:', logFile.path); console.log('File size:', logFile.size); // Read all log content const logs = log.transports.file.readAllLogs(); logs.forEach(({ path: p, lines }) => { console.log(`File: ${p}, Lines: ${lines.length}`); console.log(lines.slice(-5).join('\n')); // last 5 lines }); // Clear the log file logFile.clear(); ``` -------------------------------- ### Custom Event Format Function Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md Define a custom function to format event data. This example serializes the arguments to a JSON string. ```javascript log.eventLogger.format = ({ args, event, eventName, eventSource }) => { return [`${eventSource}#${eventName}:`, JSON.stringify(args)]; }; ``` -------------------------------- ### Custom Formatter for Console Messages Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md Create a specific formatter for 'console-message' events from webContents. This example filters messages based on level and formats the output. ```javascript log.eventLogger.formatters.webContents['console-message'] = ({ args: [level, message, line, sourceId], event, eventName, eventSource }) => { const webContents = event.sender; if (level > 2) { return undefined; } return { message, source: `${sourceId}:${line}`, url: webContents?.getURL() }; }; ``` -------------------------------- ### Add Custom Log Levels Source: https://context7.com/megahertz/electron-log/llms.txt Extend electron-log with custom log levels using `addLevel`. Provide the level name and its severity index. This example adds a 'notice' level between 'verbose' and 'info'. ```javascript import log from 'electron-log/main'; // Add 'notice' between 'verbose' (index 3) and 'info' (index 2) log.addLevel('notice', 2); log.notice('This is a notice-level message'); // Output: 12:00:00.001 › This is a notice-level message ``` -------------------------------- ### Stop Logging Events Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md Halts the logging of electron events that was previously started. ```APIDOC ## log.eventLogger.stopLogging() ### Description Stop saving logs. ### Method `log.eventLogger.stopLogging()` ``` -------------------------------- ### Start catching unhandled errors Source: https://github.com/megahertz/electron-log/blob/master/README.md Enable electron-log to automatically catch and log unhandled errors and rejected promises. This helps in debugging application stability issues. ```javascript log.errorHandler.startCatching(options?); ``` -------------------------------- ### Override Default Log Path (v4) Source: https://github.com/megahertz/electron-log/blob/master/docs/migration.md Customize the log file path in the file transport by providing a custom resolvePath function. This example shows how to use the library's default directory and filename. ```javascript log.transports.file.resolvePath = (variables) => { return path.join(variables.libraryDefaultDir, variables.fileName); } ``` -------------------------------- ### Redact Sensitive Values in File Logs Source: https://context7.com/megahertz/electron-log/llms.txt Add a transform to the file transport to preprocess log messages. This example redacts 'password=...' values before they are written to the file. ```javascript import log from 'electron-log/main'; // Redact sensitive values in file logs log.transports.file.transforms.push(({ data }) => { return data.map((item) => typeof item === 'string' ? item.replace(/password=\S+/gi, 'password=***') : item, ); }); ``` -------------------------------- ### Intercept and Filter Log Messages with Hooks Source: https://context7.com/megahertz/electron-log/llms.txt Use log hooks to intercept and filter messages sent to transports. Return `false` to drop a message for a specific transport, or return a modified message object to alter it before it's logged. This example prevents passwords from being written to the file transport and redacts token data. ```javascript import log from 'electron-log/main'; // Prevent passwords from reaching the file transport // and truncate token data log.hooks.push((message, transport, transportName) => { if (transportName !== 'file') return message; if (message.data.join(' ').includes('password')) { return false; // drop this message for the file transport } if (message.data.join(' ').includes('token')) { return { ...message, data: ['[TOKEN REDACTED]'] }; } return message; }); ``` -------------------------------- ### Basic Logging in Main Process Source: https://context7.com/megahertz/electron-log/llms.txt Import from 'electron-log/main' and call log.initialize() before creating any windows. This injects the IPC preload script into all renderer sessions automatically. Supports multiple log levels and overriding console functions. ```javascript // main.js import log from 'electron-log/main'; log.initialize(); // must be called before BrowserWindow creation log.error('Something went wrong', new Error('fail')); log.warn('Low disk space'); log.info('App started', { version: '1.0.0' }); log.verbose('Verbose detail'); log.debug('Debug value', { x: 42 }); log.silly('Very noisy trace'); // Shortcut: log.log === log.info log.log('Same as info'); // Override global console Object.assign(console, log.functions); console.warn('Now routed through electron-log'); ``` -------------------------------- ### Initialize electron-log in Main Process (v5+) Source: https://github.com/megahertz/electron-log/blob/master/docs/migration.md Configure electron-log in the main process before creating any windows. This is necessary for renderer processes to communicate with the main process for logging. ```javascript import log from 'electron-log/main'; // It preloads electron-log IPC code in renderer processes log.initialize(); ``` -------------------------------- ### Initialize logger in Main Process Source: https://github.com/megahertz/electron-log/blob/master/README.md Import and initialize the logger in the main process. This makes the logger available for use. ```javascript import log from 'electron-log/main'; // Initialize the logger to be available in renderer process log.initialize(); log.info('Log from the main process'); ``` -------------------------------- ### Initialize Logger in Main Process (Bundler) Source: https://github.com/megahertz/electron-log/blob/master/docs/initialize.md Use this in your main process when using a bundler with contextIsolation/sandbox enabled. This sets up the logger to handle messages from renderer processes. ```javascript import log from 'electron-log/main'; log.initialize(); ``` -------------------------------- ### Manually Handle an Error Source: https://github.com/megahertz/electron-log/blob/master/docs/errors.md Processes a given error object. This method can be used even if error catching has not been explicitly started. ```APIDOC ## log.errorHandler.handle(error, options?) ### Description Process an error manually. This function works even if catching is not started. ### Method `log.errorHandler.handle` ### Parameters - **error** (Error) - Required - The error object to process. - **options** ({ showDialog?, onError? }) - Optional - Same options as `startCatching` can be passed to customize handling. ``` -------------------------------- ### log.initialize() via Manual Preload Injection Source: https://context7.com/megahertz/electron-log/llms.txt Manually import the preload bridge ('electron-log/preload') inside your own preload script instead of using log.initialize(). This sets up the IPC bridge, and the renderer then uses 'electron-log/renderer' as usual. ```javascript // preload.js import 'electron-log/preload'; // No logger is exported here — this only sets up the IPC bridge. // The renderer then uses electron-log/renderer as usual. ``` -------------------------------- ### Open Second Renderer Process with Query Parameters Source: https://github.com/megahertz/electron-log/blob/master/e2e/multiple-renderers/index.html Opens a new window to `index-second.html`, passing query parameters based on the current URL. This is useful for initializing child windows with specific states or test conditions. ```javascript const url = new URL(window.location.href); const query = url.searchParams.get('test') === 'true' ? 'test=true' : ''; const dirname = url.searchParams.get('dirname'); const wnd = window.open(`file://${dirname}/index-second.html?${query}`); ``` -------------------------------- ### Basic Logging in Renderer Process Source: https://context7.com/megahertz/electron-log/llms.txt Import from 'electron-log/renderer' when using a bundler. Without a bundler, use the injected '__electronLog' global. Logs from the renderer process are forwarded to the main process via IPC. ```typescript // renderer.ts (with bundler) import log from 'electron-log/renderer'; log.info('Renderer started'); log.error('UI error', new Error('render failure')); // Without a bundler (contextIsolation enabled, no bundler) __electronLog.info('Log from unbundled renderer'); ``` -------------------------------- ### Configure File Transport Options Source: https://context7.com/megahertz/electron-log/llms.txt Customize file transport settings like log path, file size, rotation callbacks, serialization depth, and format. Ensure imports are present for path manipulation. ```javascript import log from 'electron-log/main'; import path from 'node:path'; // Custom log file location log.transports.file.resolvePathFn = (variables) => path.join(variables.userData, 'logs', 'app.log'); // Use Electron's built-in logs path log.transports.file.resolvePathFn = (variables) => path.join(variables.electronDefaultDir, variables.fileName); // Override app name used in the default path log.transports.file.setAppName('MyApp'); // Custom format log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}] {text}'; // Increase max file size before rotation (default 1 MB) log.transports.file.maxSize = 5 * 1024 * 1024; // 5 MB // Custom rotation callback log.transports.file.archiveLogFn = (oldFile) => { const fs = require('fs'); fs.rmSync(oldFile.toString(), { force: true }); }; // Control serialization depth for objects log.transports.file.inspectOptions = { depth: 3 }; ``` -------------------------------- ### Log from Node.js or NW.js Source: https://github.com/megahertz/electron-log/blob/master/README.md Import and use the logger in a Node.js or NW.js environment. ```typescript import log from 'electron-log/node'; log.info('Log from the nw.js or node.js'); ``` -------------------------------- ### Basic Logging in Node.js / NW.js Source: https://context7.com/megahertz/electron-log/llms.txt Use 'electron-log/node' for pure Node.js or NW.js environments where Electron IPC is unavailable. This allows logging directly without Electron's IPC mechanism. ```typescript // server.ts import log from 'electron-log/node'; log.info('Server started on port 3000'); log.error('DB connection failed', { host: 'localhost', port: 5432 }); ``` -------------------------------- ### Log from Second Renderer Process Source: https://github.com/megahertz/electron-log/blob/master/e2e/multiple-renderers/index-second.html Logs a warning message from the second renderer process. If the URL includes 'test=true', the window will close after a short delay. ```javascript __electronLog.warn('log from the second renderer process'); if (window.location.href.includes('test=true')) { setTimeout(() => window.close(), 50); } ``` -------------------------------- ### Initialize Logger with Custom Sessions Source: https://github.com/megahertz/electron-log/blob/master/docs/initialize.md Configure the logger to use specific sessions by providing a function that returns an array of sessions. Ensure custom sessions are initialized after `log.initialize()` or passed here. ```javascript log.initialize({ getSessions: () => [customSession] }); ``` -------------------------------- ### Add Custom Transform to File Transport Source: https://github.com/megahertz/electron-log/blob/master/docs/extend.md Append a custom function to the file transport's transforms array to modify log message data before it's written. This example prepends '[PAYNMENT]' to messages containing 'paynment'. ```javascript log.transports.file.transforms.push(({ data, logger, message, transport }) => { if (data.join().includes('paynment')) { return ['[PAYNMENT]', ...data]; } return data; }); ``` -------------------------------- ### Log from Renderer using Global Variable Source: https://github.com/megahertz/electron-log/blob/master/docs/initialize.md Log directly from the renderer process using the `__electronLog` global variable. This method is suitable for environments without bundling and with isolated contexts. ```javascript __electronLog.info('Log from the renderer'); ``` -------------------------------- ### Create multiple logger instances Source: https://github.com/megahertz/electron-log/blob/master/README.md Instantiate separate logger objects with distinct configurations. This allows for managing different logging behaviors or destinations within the same application. ```javascript import log from 'electron-log/main'; const anotherLogger = log.create({ logId: 'anotherInstance' }); ``` -------------------------------- ### Log from Renderer Process (Bundler) Source: https://github.com/megahertz/electron-log/blob/master/docs/initialize.md Import and use the renderer logger in your renderer process files when using a bundler. This sends logs to the main process. ```typescript import log from 'electron-log/renderer'; log.info('Log from the renderer'); ``` -------------------------------- ### Log from Renderer Process Source: https://github.com/megahertz/electron-log/blob/master/e2e/isolation-preload/index.html Logs a warning message from the renderer process. Closes the window if the URL contains 'test=true'. ```javascript log.warn('log from the renderer process'); if (window.location.href.includes('test=true')) { setTimeout(() => window.close(), 50); } ``` -------------------------------- ### Log from Renderer Process (v5+) Source: https://github.com/megahertz/electron-log/blob/master/docs/migration.md Import and use the renderer-specific electron-log module to send log messages from the renderer process. ```typescript import log from 'electron-log/renderer'; log.info('Log from the renderer'); ``` -------------------------------- ### Custom Event Formatting Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md Demonstrates how to define a custom format for logged events using a function. ```APIDOC ## log.eventLogger.format ### Description Custom format function example. ### Code Example ```js log.eventLogger.format = ({ args, event, eventName, eventSource }) => { return [`${eventSource}#${eventName}:`, JSON.stringify(args)]; }; ``` ``` -------------------------------- ### Configure File Transport Path Source: https://github.com/megahertz/electron-log/blob/master/README.md Customize the log file path for the file transport by providing a resolvePathFn. Ensure the 'path' module is imported. ```javascript log.transports.file.resolvePathFn = () => path.join(APP_DATA, 'logs/main.log'); ``` -------------------------------- ### Log Info in Isolation Context Sandbox Source: https://github.com/megahertz/electron-log/blob/master/e2e/isolation-context-sandbox/index.html Logs an informational message using the global __electronLog object within an isolation context sandbox. If the test parameter is present in the URL, the window will close after a short delay. ```javascript __electronLog.info('log through global object'); if (window.location.href.includes('test=true')) { setTimeout(() => window.close(), 50); } ``` -------------------------------- ### Configurable Events Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md Shows the default configuration for which events are logged and how to modify this selection. ```APIDOC ## log.eventLogger.events ### Description Allow switching specific events on/off easily. ### Default Configuration ```js log.eventLogger.events = { app: { 'certificate-error': true, 'child-process-gone': true, 'render-process-gone': true, }, webContents: { 'did-fail-load': true, 'did-fail-provisional-load': true, 'plugin-crashed': true, 'preload-error': true, 'unresponsive': true, } } ``` ``` -------------------------------- ### Add Custom Log Level Source: https://github.com/megahertz/electron-log/blob/master/docs/extend.md Define a new log level, 'notice', and assign it a numerical index. This allows you to use the new level in your logging calls. ```javascript log.addLevel('notice', 2); log.notice('New level added'); ``` -------------------------------- ### Format Logs with a Function Source: https://github.com/megahertz/electron-log/blob/master/docs/transports/format.md Use a function to format log messages for advanced control. The function receives log details and should return an array of strings. ```javascript import util from 'node:util'; log.transports.console.format = ({ data, level, message }) => { const text = util.format(...data); return [ message.date.toISOString().slice(11, -1), `[${level}]`, text ]; }; ``` -------------------------------- ### Create and Use Named Log Scopes Source: https://context7.com/megahertz/electron-log/llms.txt Utilize log.scope() to create isolated logger instances with labeled prefixes for better log organization. Configure label padding for consistent formatting. ```javascript import log from 'electron-log/main'; const authLog = log.scope('auth'); const dbLog = log.scope('db'); authLog.info('User logged in', { userId: 42 }); // → 12:05:01.123 (auth) › User logged in { userId: 42 } dbLog.error('Query failed', { query: 'SELECT *', ms: 1500 }); // → 12:05:01.456 (db) › Query failed { query: 'SELECT *', ms: 1500 } // Disable automatic padding of scope labels log.scope.labelPadding = false; // Set a fixed max label width log.scope.labelPadding = 10; ``` -------------------------------- ### Create Multiple Isolated Logger Instances Source: https://context7.com/megahertz/electron-log/llms.txt Generate independent logger instances using log.create() with custom configurations for paths, levels, and transports, without affecting the default logger. ```javascript import log from 'electron-log/main'; const auditLog = log.create({ logId: 'audit' }); // Configure the audit logger independently auditLog.transports.file.resolvePathFn = (v) => require('path').join(v.userData, 'logs', 'audit.log'); auditLog.transports.file.level = 'info'; auditLog.transports.console.level = false; // silent in console auditLog.info('User action', { action: 'delete', resource: 'post/42' }); // Default logger is unaffected log.debug('Default logger still works'); ``` -------------------------------- ### Configure and Use Remote Transport Source: https://github.com/megahertz/electron-log/blob/master/docs/transports/remote.md Set the log level and URL for the remote transport, then send a warning message. The transport will automatically format the message as a JSON POST request. ```javascript log.transports.remote.level = 'warn'; log.transports.remote.url = 'https://example.com/myapp/add-log' log.warn('Some problem appears', { error: e }); ``` -------------------------------- ### Define Custom Log Variables Source: https://context7.com/megahertz/electron-log/llms.txt Attach custom key-value pairs to the logger for use in all format templates. Ensure variables are defined before the format is applied. ```javascript import log from 'electron-log/main'; log.variables.label = 'main'; log.variables.env = process.env.NODE_ENV ?? 'development'; log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{env}] [{label}] [{level}] {text}'; // → [2024-01-15 12:00:00.123] [development] [main] [info] App started ``` -------------------------------- ### Console Transport - Format, Colors, and writeFn Source: https://context7.com/megahertz/electron-log/llms.txt Configures the console transport for string templates, custom format functions, per-level colors, and a custom write function. Options include disabling colors and the console transport entirely. ```javascript import log from 'electron-log/main'; import util from 'node:util'; // String template (tokens: {y} {m} {d} {h} {i} {s} {ms} {level} {text} {scope}) log.transports.console.format = '[{h}:{i}:{s}.{ms}] [{level}] {text}'; // Custom format function log.transports.console.format = ({ data, level, message }) => { const text = util.format(...data); return [message.date.toISOString().slice(11, -1), `[${level}]`, text]; }; // Per-level color map log.transports.console.colorMap = { error: 'red', warn: 'yellow', info: 'cyan', verbose: 'unset', debug: 'gray', silly: 'gray', }; // Inline color markers (main + DevTools console) log.info('%cRed text. %cGreen text', 'color: red', 'color: green'); // Force disable colors log.transports.console.useStyles = false; // Custom write function (e.g., pipe to a third-party sink) log.transports.console.writeFn = ({ message }) => { process.stdout.write(util.format(...message.data) + '\n'); }; // Disable console transport entirely log.transports.console.level = false; ``` -------------------------------- ### Configure Remote Transport Source: https://context7.com/megahertz/electron-log/llms.txt Set up the remote transport to send logs to an HTTP endpoint. Configure the URL, log level, client metadata, and serialization depth. ```javascript import log from 'electron-log/main'; // Basic setup log.transports.remote.level = 'warn'; log.transports.remote.url = 'https://example.com/api/logs'; // Custom client metadata log.transports.remote.client = { name: 'my-app', version: '1.0.0' }; // Limit object serialization depth to reduce payload size log.transports.remote.depth = 3; // Extra HTTP options (e.g., custom headers, auth) log.transports.remote.requestOptions = { headers: { Authorization: 'Bearer my-token' }, }; ``` -------------------------------- ### Initialize Logger to Spy on Console.log Source: https://github.com/megahertz/electron-log/blob/master/docs/initialize.md Enable spying on `console.log` calls in the renderer process. This allows the main process to capture logs made via `console.log`, but it has limitations with logging objects. ```javascript import log from 'electron-log/main'; log.initialize({ spyRendererConsole: true }); ``` -------------------------------- ### esbuild ESM Workaround Configuration Source: https://github.com/megahertz/electron-log/blob/master/e2e/esbuild-esm/README.md This configuration is necessary for esbuild to handle ESM imports correctly. It provides a banner with import logic. ```javascript const esBuildOptions = { banner: { js: 'import { createRequire } from \'module\';\n' + 'const require = createRequire(import.meta.url);', }, ... }; ``` -------------------------------- ### Set Logging Options Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md Allows modification of the current logging options for event logging. ```APIDOC ## log.eventLogger.setOptions(options) ### Description Set logging options. ### Method `log.eventLogger.setOptions(options: EventLoggerOptions)` ``` -------------------------------- ### Implement buffering for logs Source: https://github.com/megahertz/electron-log/blob/master/README.md Utilize the buffering mechanism to temporarily store log messages before committing or rejecting them. This is useful for conditionally logging verbose information, especially during error handling. ```javascript import log from 'electron-log/main'; log.buffering.begin(); try { log.info('First silly message'); // do somethings complex log.info('Second silly message'); // do something else // Finished fine, we don't need these logs anymore log.buffering.reject(); } catch (e) { log.buffering.commit(); log.warn(e); } ``` -------------------------------- ### Log Level Configuration Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md Specifies the log level used for event logging, with 'warn' as the default. ```APIDOC ## log.eventLogger.level ### Description Which log level is used for logging. ### Default `'warn'` ``` -------------------------------- ### Inject Preload Script Manually Source: https://github.com/megahertz/electron-log/blob/master/docs/initialize.md Manually inject the electron-log preload script into your preload script by adding the import statement. This is an alternative to calling `log.initialize()`. ```javascript import 'electron-log/preload'; ``` -------------------------------- ### Log Warning in nw.js Source: https://github.com/megahertz/electron-log/blob/master/e2e/nwjs/index.html Use this snippet to log a warning message within an nw.js application. Ensure the 'nw.gui' and the logging library are correctly imported. ```javascript const { App } = require('nw.gui'); const log = require('../..'); log.warn('log from nw.js'); if (App.argv.indexOf('--test') !== -1) { setTimeout(() => App.quit(), 50); } ``` -------------------------------- ### File Transport Options Source: https://github.com/megahertz/electron-log/blob/master/docs/transports/file.md Configuration options for the file transport. These allow customization of log file behavior, including naming, formatting, size limits, and rotation. ```APIDOC ## File Transport Options ### `archiveLogFn` {(oldLogFile: LogFile) => void} Callback which is called on log rotation. You can override it if you need custom log rotation behavior. This function should remove old file synchronously. ### `fileName` {string} The actual file name without path. ### `format` {string | (params: FormatParams) => any[]} Determines how to serialize log message while writing to a file. ### `inspectOptions` {InspectOptions} How to serialize objects passed to log function. ### `level` {LogLevel | false} Filter log messages which can be sent via the transport. ### `maxSize` {number} Maximum size of a log file in bytes. When a log file exceeds this limit, it will be moved to {file name}.old.log file. You can set it to 0 to disable log rotation. ### `resolvePathFn` {(variables: PathVariables, message?: LogMessage) => string} Allows to set a custom path for a log file. Directory hierarchy will be created automatically if necessary. ### `sync` {boolean} Whether to write a log file synchronously. ### `writeOptions` {WriteOptions} Options for fs.writeFile ``` -------------------------------- ### File Transport Methods Source: https://github.com/megahertz/electron-log/blob/master/docs/transports/file.md Methods available for interacting with the file transport, such as retrieving the current log file or reading all log contents. ```APIDOC ## File Transport Methods ### `getFile(message?: Partial) => LogFile` Return the current file instance used for the transport. The `message` argument is optional and only required if you define log path inside `resolvePath` callback depending on a message. ### `readAllLogs() => Array<{ path: string, lines: string[] }>` Reads content of all log files. Be careful, if you use multiple log directories through overriding resolvePath, it won't return all the files. ### `setAppName(appName: string)` Overrides appName used for resolving the log path ``` -------------------------------- ### Renderer Process Logging Source: https://github.com/megahertz/electron-log/blob/master/e2e/isolation-none/index.html Logs information and errors from the renderer process. Ensures file transport is loaded and handles potential errors. ```javascript const log = require('../..'); log.info('log from the renderer process'); if (log.transports.file) { log.error(new Error('Should load renderer code')); } if (window.location.href.includes('test=true')) { setTimeout(() => window.close(), 50); } ``` -------------------------------- ### Conditional Log Flushing with Buffering Source: https://context7.com/megahertz/electron-log/llms.txt Buffer log messages during a complex operation and either commit (emit all) or reject (discard all) at the end. Use `log.buffering.begin()`, `log.buffering.commit()`, and `log.buffering.reject()`. ```javascript import log from 'electron-log/main'; async function riskyOperation() { log.buffering.begin(); try { log.verbose('Step 1: connecting to DB'); await db.connect(); log.verbose('Step 2: running migration'); await db.migrate(); log.verbose('Step 3: done'); // Everything succeeded — discard verbose noise log.buffering.reject(); } catch (e) { // Something failed — flush all buffered messages for diagnostics log.buffering.commit(); log.error('Operation failed', e); } } ``` -------------------------------- ### Initialize Logger without Future Session Injection Source: https://github.com/megahertz/electron-log/blob/master/docs/initialize.md Disable the automatic injection of the preload script into future sessions by setting `includeFutureSession` to `false` during initialization. ```javascript log.initialize({ includeFutureSession: false }); ``` -------------------------------- ### Default Event Configuration Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md View the default configuration for which Electron events are logged. You can modify this object to enable or disable specific events. ```javascript log.eventLogger.events = { app: { 'certificate-error': true, 'child-process-gone': true, 'render-process-gone': true, }, webContents: { 'did-fail-load': true, 'did-fail-provisional-load': true, 'plugin-crashed': true, 'preload-error': true, 'unresponsive': true, } } ``` -------------------------------- ### Create and use a logging scope Source: https://github.com/megahertz/electron-log/blob/master/README.md Define specific scopes for logging messages, which helps in categorizing and identifying log entries originating from different parts of the application. Scope labels are padded by default. ```javascript import log from 'electron-log/main'; const userLog = log.scope('user'); userLog.info('message with user scope'); ``` -------------------------------- ### Define Custom Log Variables Source: https://github.com/megahertz/electron-log/blob/master/docs/transports/format.md You can define your own variables to be used in log message templates. Assign a value to `log.variables.`. ```javascript log.variables.label = 'dev'; log.transports.console.format = '[{h}:{i}:{s}.{ms}] [{label}] {text}'; ``` -------------------------------- ### Override console.log with electron-log Source: https://github.com/megahertz/electron-log/blob/master/README.md Replace the default console.log function with electron-log's logging functionality. This allows all subsequent console.log calls to be handled by electron-log. ```javascript console.log = log.log; ``` -------------------------------- ### Log Scope Configuration Source: https://github.com/megahertz/electron-log/blob/master/docs/events.md Defines the log scope for event logging, with an empty string as the default. ```APIDOC ## log.eventLogger.scope ### Description Which log scope is used for logging. ### Default `''` ``` -------------------------------- ### Log Critical Electron Events Source: https://context7.com/megahertz/electron-log/llms.txt Automatically save critical lifecycle and crash events from `app` and `webContents`. Configure which events to log and customize the event format. ```javascript import log from 'electron-log/main'; log.eventLogger.startLogging({ level: 'warn', // Toggle individual events events: { app: { 'certificate-error': true, 'child-process-gone': true, 'render-process-gone': true, }, webContents: { 'did-fail-load': true, 'did-fail-provisional-load': true, 'plugin-crashed': true, 'preload-error': true, 'unresponsive': true, }, }, // Custom event formatter format: ({ eventSource, eventName, args }) => [`${eventSource}#${eventName}`, ...args], }); // Stop later // log.eventLogger.stopLogging(); ``` -------------------------------- ### Default Path Resolution Function Source: https://github.com/megahertz/electron-log/blob/master/docs/transports/file.md This is the default function used to resolve the log file path. It joins the library's default directory with the specified file name. You can customize this to define a custom path for your log files. ```javascript function resolvePath(variables) { return path.join(variables.libraryDefaultDir, variables.fileName); } ``` -------------------------------- ### Add a Hook to Control Logging Source: https://github.com/megahertz/electron-log/blob/master/docs/extend.md Implement a hook to gain fine-grained control over log messages. This hook skips 'file' transport for messages containing 'password' and modifies messages containing 'token'. ```javascript log.hooks.push((message, transport, transportName) => { if (transportName !== 'file') { return message; } if (message.data.join().includes('password')) { return false; } if (message.data.join().includes('token')) { return { ...message, data: message.data.slice(0, 2), }; } return message; }); ``` -------------------------------- ### Log with colors in electron-log Source: https://github.com/megahertz/electron-log/blob/master/README.md Utilize colors for logging messages in both the main and DevTools console. Supports standard color names and other CSS properties for DevTools. ```javascript log.info('%cRed text. %cGreen text', 'color: red', 'color: green') ``` -------------------------------- ### log.variables — custom format variables Source: https://context7.com/megahertz/electron-log/llms.txt Attach custom key-value pairs to the logger that are available in all format templates. These variables can be used to enrich log messages with contextual information. ```APIDOC ## log.variables — custom format variables Attach custom key-value pairs to the logger that are available in all format templates. ```js import log from 'electron-log/main'; log.variables.label = 'main'; log.variables.env = process.env.NODE_ENV ?? 'development'; log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{env}] [{label}] [{level}] {text}'; // → [2024-01-15 12:00:00.123] [development] [main] [info] App started ``` ``` -------------------------------- ### log.addLevel() — custom log levels Source: https://context7.com/megahertz/electron-log/llms.txt Enables the addition of custom log levels to the electron-log system, allowing for more granular control over log message severity. ```APIDOC ## log.addLevel() — custom log levels Add new levels anywhere in the severity hierarchy. ```js import log from 'electron-log/main'; // Add 'notice' between 'verbose' (index 3) and 'info' (index 2) log.addLevel('notice', 2); log.notice('This is a notice-level message'); // Output: 12:00:00.001 › This is a notice-level message // TypeScript: extend LogFunctions in electron-log.extend.d.ts // import 'electron-log' // declare module 'electron-log' { // interface LogFunctions { notice(...params: any[]): void; } // } ``` ``` -------------------------------- ### log.errorHandler — catch unhandled errors and rejections Source: https://context7.com/megahertz/electron-log/llms.txt Automatically captures uncaught exceptions and unhandled promise rejections and logs them. This helps in diagnosing and reporting unexpected application failures. ```APIDOC ## log.errorHandler — catch unhandled errors and rejections Automatically captures uncaught exceptions and unhandled promise rejections and logs them. ```js import log from 'electron-log/main'; import electron from 'electron'; log.errorHandler.startCatching({ showDialog: false, // suppress default Electron error dialog onError({ createIssue, error, processType, versions }) { if (processType === 'renderer') return; // renderer errors handled separately electron.dialog.showMessageBox({ title: 'Unexpected Error', message: error.message, detail: error.stack, type: 'error', buttons: ['Ignore', 'Report', 'Exit'], }).then(({ response }) => { if (response === 1) { createIssue('https://github.com/my-org/my-app/issues/new', { title: `Error in ${versions.app}`, body: '```\n' + error.stack + '\n```\n\nOS: ' + versions.os, }); } else if (response === 2) { electron.app.quit(); } }); }, }); // Stop catching later if needed // log.errorHandler.stopCatching(); // Handle a specific error manually (works without startCatching) log.errorHandler.handle(new Error('Manual error'), { showDialog: false }); ``` ``` -------------------------------- ### log.eventLogger — log critical Electron events Source: https://context7.com/megahertz/electron-log/llms.txt Automatically saves critical lifecycle and crash events from `app` and `webContents` to the log. This provides visibility into important application and rendering process events. ```APIDOC ## log.eventLogger — log critical Electron events Automatically saves critical lifecycle and crash events from `app` and `webContents` to the log. ```js import log from 'electron-log/main'; log.eventLogger.startLogging({ level: 'warn', // Toggle individual events events: { app: { 'certificate-error': true, 'child-process-gone': true, 'render-process-gone': true, }, webContents: { 'did-fail-load': true, 'did-fail-provisional-load': true, 'plugin-crashed': true, 'preload-error': true, 'unresponsive': true, }, }, // Custom event formatter format: ({ eventSource, eventName, args }) => [`${eventSource}#${eventName}`, ...args], }); // Stop later // log.eventLogger.stopLogging(); ``` ``` -------------------------------- ### Default colorMap for Console Transport Source: https://github.com/megahertz/electron-log/blob/master/docs/transports/console.md This is the default map of log levels to colors used by the console transport. It defines the color for each log level. ```javascript { error: 'red', warn: 'yellow', info: 'cyan', verbose: 'unset', debug: 'gray', silly: 'gray', default: 'unset', } ``` -------------------------------- ### Send Log Message Directly via IPC Source: https://github.com/megahertz/electron-log/blob/master/docs/initialize.md Send log messages directly from the renderer process using `ipcRenderer.send` to the `__ELECTRON_LOG__` channel. This method bypasses the renderer logger instance and requires constructing a LogMessage-like object. ```javascript import { ipcRenderer } from 'electron'; ipcRenderer.send('__ELECTRON_LOG__', { // LogMessage-like object data: ['Log from a renderer'], level: 'info', variables: { processType: 'renderer' }, // ... some other optional fields like scope, logId and so on }); ``` -------------------------------- ### Custom transports — replace or add sinks Source: https://context7.com/megahertz/electron-log/llms.txt A transport is any function `(msg: LogMessage) => void`. Replace built-in transports or add new ones to direct log output to different destinations like databases or custom streams. ```APIDOC ## Custom transports — replace or add sinks A transport is any function `(msg: LogMessage) => void`. Replace built-ins or add new ones freely. ```js import log from 'electron-log/main'; import util from 'util'; // Replace the console transport with a custom implementation log.transports.console = (message) => { const text = util.format.apply(util, message.data); process.stdout.write(`[${message.date.toLocaleTimeString()} ${message.level}] ${text}\n`); }; // Add a brand-new named transport (e.g., write to SQLite) log.transports.sqlite = (message) => { db.run( 'INSERT INTO logs (level, text, ts) VALUES (?, ?, ?)', [message.level, util.format(...message.data), message.date.toISOString()], ); }; log.transports.sqlite.level = 'info'; log.transports.sqlite.transforms = []; ``` ``` -------------------------------- ### Override Console Transport Source: https://github.com/megahertz/electron-log/blob/master/docs/extend.md Replace the default console transport to customize log output format. Be aware that overriding a transport will reset its default options. ```javascript import util from 'util'; log.transports.console = (message) => { const text = util.format.apply(util, message.data); console.log(`[${message.date.toLocaleTimeString()} ${message.level}] ${text}`); }; ```