Multiple output destinations for log messages including console, files, IPC communication, and remote HTTP endpoints. Each transport is independently configurable with its own level filtering and message formatting.
Outputs log messages to console (main process) or DevTools console (renderer process) with color support and customizable formatting.
interface ConsoleTransport extends Transport {
/** Messages with level lower than will be dropped */
level: LevelOption;
/** String template or function for message serialization */
format: Format | string;
/** A mapping of log levels to their corresponding color name */
colorMap: Record<LogLevel, string>;
/** Use styles even if TTY isn't attached */
useStyles: boolean;
/** Override message printing */
writeFn(options: { message: LogMessage }): void;
}Usage Examples:
const log = require('electron-log');
// Configure console transport
log.transports.console.level = 'debug';
log.transports.console.format = '{h}:{i}:{s} [{level}] {text}';
// Custom colors
log.transports.console.colorMap = {
error: 'red',
warn: 'yellow',
info: 'white',
verbose: 'gray',
debug: 'blue',
silly: 'magenta'
};
// Force colors even without TTY
log.transports.console.useStyles = true;
// Custom write function
log.transports.console.writeFn = ({ message }) => {
console.log(`[CUSTOM] ${message.data.join(' ')}`);
};Writes log messages to files with automatic rotation, customizable paths, and comprehensive file management.
interface FileTransport extends Transport {
/** Messages with level lower than will be dropped */
level: LevelOption;
/** Filename without path, main.log (or renderer.log) by default */
fileName: string;
/** String template or function for message serialization */
format: Format | string;
/** Maximum size of log file in bytes, 1048576 (1mb) by default */
maxSize: number;
/** Whether to write a log file synchronously. Default to true */
sync: boolean;
/** Serialization options */
inspectOptions: InspectOptions;
/** Options used when writing a file */
writeOptions?: WriteOptions;
/** Allow to change log file path dynamically */
resolvePathFn: (variables: PathVariables, message?: LogMessage) => string;
/** Function which is called on log rotation */
archiveLogFn: (oldLogFile: LogFile) => void;
/** Return the current log file instance */
getFile(message?: Partial<LogMessage>): LogFile;
/** Reads content of all log files */
readAllLogs(options?: { fileFilter?: (logPath: string) => boolean }): Array<{ path: string; lines: string[] }>;
/** Override appName used for resolving log path */
setAppName(appName: string): void;
}Usage Examples:
const log = require('electron-log');
// Basic file transport configuration
log.transports.file.level = 'info';
log.transports.file.maxSize = 10 * 1024 * 1024; // 10MB
log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}] [{level}] {text}';
// Custom file name
log.transports.file.fileName = 'application.log';
// Custom path resolution
log.transports.file.resolvePathFn = (variables) => {
return path.join(variables.userData, 'custom-logs', variables.fileName);
};
// Custom log rotation
log.transports.file.archiveLogFn = (oldLogFile) => {
const timestamp = new Date().toISOString().slice(0, 10);
const archivePath = oldLogFile.path.replace('.log', `-${timestamp}.log`);
fs.renameSync(oldLogFile.path, archivePath);
};
// Access log file
const logFile = log.transports.file.getFile();
console.log('Log file path:', logFile.path);
console.log('Bytes written:', logFile.bytesWritten);
// Read all log files
const allLogs = log.transports.file.readAllLogs();
allLogs.forEach(({ path, lines }) => {
console.log(`File: ${path}, Lines: ${lines.length}`);
});
// Clear current log file
logFile.clear();Enables communication between main and renderer processes for cross-process logging.
interface IpcTransport extends Transport {
/** Messages with level lower than will be dropped */
level: LevelOption;
}Usage Examples:
// Main process
const log = require('electron-log/main');
log.initialize(); // Enables IPC transport for renderer processes
// Renderer process
const log = require('electron-log/renderer');
log.info('This message will appear in main process console');
// Configure IPC transport
log.transports.ipc.level = 'debug';Sends log messages to remote HTTP endpoints as JSON POST requests.
interface RemoteTransport extends Transport {
/** Messages with level lower than will be dropped */
level: LevelOption;
/** Server URL */
url: string;
/** Client information which will be sent in each request together with a message body */
client?: object;
/** How deep to serialize complex objects */
depth?: number;
/** Additional options for the HTTP request */
requestOptions?: RequestOptions;
/** Callback which is called on request error */
processErrorFn: (error: Error) => void;
/** Callback which transforms request body to string */
makeBodyFn: (options: { logger: Logger; message: LogMessage; transport: Transport }) => any;
/** Callback which allows to customize request sending */
sendRequestFn: (options: { serverUrl: string; requestOptions: RequestOptions; body: any }) => ClientRequest;
}Usage Examples:
const log = require('electron-log');
// Configure remote transport
log.transports.remote.level = 'warn';
log.transports.remote.url = 'https://api.myapp.com/logs';
// Custom client information
log.transports.remote.client = {
name: 'MyElectronApp',
version: '1.0.0',
userId: 'user123'
};
// Custom request options
log.transports.remote.requestOptions = {
headers: {
'Authorization': 'Bearer token123',
'Content-Type': 'application/json'
},
timeout: 5000
};
// Custom error handling
log.transports.remote.processErrorFn = (error) => {
console.error('Failed to send log to remote server:', error.message);
};
// Custom body formatting
log.transports.remote.makeBodyFn = ({ message, logger }) => {
return JSON.stringify({
timestamp: message.date.toISOString(),
level: message.level,
message: message.data.join(' '),
logId: logger.logId,
client: log.transports.remote.client
});
};Common transport properties and management.
interface Transport {
(message: LogMessage): void;
/** Messages with level lower than will be dropped */
level: LevelOption;
/** Transform functions applied before output */
transforms: TransformFn[];
}
interface TransportAccess {
/** Available transports object */
transports: { [key: string]: Transport | null };
}Usage Examples:
const log = require('electron-log');
// Disable a transport
log.transports.file = null;
// Re-enable with factory
log.transports.file = log.transports.file || transportFile();
// Custom transport
log.transports.custom = (message) => {
if (message.level === 'error') {
// Send to error tracking service
sendToErrorTracker(message);
}
};
// Configure transform functions
log.transports.file.transforms = [
// Add timestamp transform
({ message }) => {
return {
...message,
data: [`[${message.date.toISOString()}]`, ...message.data]
};
}
];Template variables available for file path resolution.
interface PathVariables {
/** Per-user application data directory */
readonly appData: string;
/** Application name from productName or name of package.json */
readonly appName: string;
/** Application version from package.json */
readonly appVersion: string;
/** app.getPath('logs'). May be unavailable in old versions */
readonly electronDefaultDir?: string;
/** Name of the log file without path */
readonly fileName?: string;
/** User's home directory */
readonly home: string;
/** userData + /logs/ + fileName on Linux and Windows, ~/Library/Logs/ + appName + / + fileName on macOS */
readonly libraryDefaultDir: string;
/** Same as libraryDefaultDir, but contains '{appName}' template instead of the real application name */
readonly libraryTemplate: string;
/** OS temporary path */
readonly tempDir: string;
/** The directory for storing your app's configuration files */
readonly userData: string;
}Log file instance interface for file operations.
interface LogFile {
/** Full log file path */
readonly path: string;
/** How many bytes were written since transport initialization */
readonly bytesWritten: number;
/** Current file size */
readonly size: number;
/** Clear the log file */
clear(): boolean;
/** Emitted when there was some error while saving log file */
on(event: 'error', listener: (error: Error, file: LogFile) => void): LogFile;
}
interface WriteOptions {
/** Default 'a' */
flag?: FOpenFlags;
/** Default 0666 */
mode?: number;
/** Default 'utf8' */
encoding?: string;
}
type FOpenFlags = 'r' | 'r+' | 'rs+' | 'w' | 'wx' | 'w+' | 'wx+' | 'a' | 'ax' | 'a+' | 'ax+';type LevelOption = LogLevel | false;
type Format = string | ((params: FormatParams) => any[]);
interface FormatParams {
data: any[];
level: LogLevel;
logger: Logger;
message: LogMessage;
transport: Transport;
}
type TransformFn = (options: {
data: any[];
message: LogMessage;
transport: Transport;
logger: Logger;
}) => any;