Logger instance creation, configuration, and lifecycle management with support for multiple independent logger instances and comprehensive customization options.
Create new logger instances with custom configurations.
/**
* Create a new electron-log instance
* @param options - Logger configuration options
* @returns New logger instance with specified configuration
*/
create(options: { logId: string }): Logger;Usage Examples:
const log = require('electron-log');
// Create custom logger instances
const authLogger = log.create({ logId: 'auth' });
const dbLogger = log.create({ logId: 'database' });
const apiLogger = log.create({ logId: 'api' });
// Each logger is independent
authLogger.info('User authentication started');
dbLogger.debug('Database query executed');
apiLogger.error('API request failed');
// Configure independently
authLogger.transports.file.fileName = 'auth.log';
dbLogger.transports.file.fileName = 'database.log';Core logger properties and configuration access.
interface Logger extends LogFunctions {
/** ID of the current logger instance */
logId: string;
/** Array with all available levels */
levels: string[];
/** Transport instances */
transports: { [key: string]: Transport | null };
/** Variables used by formatters */
variables: Variables;
/** Array with all attached hooks */
hooks: Hook[];
/** Object contained only log functions */
functions: LogFunctions;
/** Buffering helper */
buffering: Buffering;
/** Error handling helper */
errorHandler: ErrorHandler;
/** Create a new scope */
scope: Scope;
}Usage Examples:
const log = require('electron-log');
// Access logger properties
console.log('Logger ID:', log.logId);
console.log('Available levels:', log.levels);
console.log('Active transports:', Object.keys(log.transports).filter(key => log.transports[key]));
// Configure variables
log.variables.appVersion = '1.0.0';
log.variables.environment = 'production';
// Access functions object
const { error, warn, info } = log.functions;Message processing hooks for custom log message manipulation.
type Hook = (
message: LogMessage,
transport?: Transport,
transportName?: string,
) => LogMessage | false;
interface HookSystem {
/** Array with all attached hooks */
hooks: Hook[];
}Usage Examples:
const log = require('electron-log');
// Add a hook to filter sensitive data
log.hooks.push((message, transport) => {
// Filter out password fields
const filteredData = message.data.map(item => {
if (typeof item === 'object' && item.password) {
return { ...item, password: '***' };
}
return item;
});
return { ...message, data: filteredData };
});
// Add a hook to add context information
log.hooks.push((message) => {
return {
...message,
data: [`[${message.logId || 'default'}]`, ...message.data]
};
});
// Hook that prevents certain messages from being logged
log.hooks.push((message) => {
if (message.data.some(item => typeof item === 'string' && item.includes('SECRET'))) {
return false; // Prevent logging
}
return message;
});Control message buffering for batch processing and conditional logging.
interface Buffering {
/** Buffered log messages */
buffer: LogMessage[];
/** Whether buffering is currently enabled */
enabled: boolean;
/**
* Start buffering log messages
*/
begin(): void;
/**
* Stop buffering and process all buffered logs
*/
commit(): void;
/**
* Stop buffering and discard all buffered logs
*/
reject(): void;
}Usage Examples:
const log = require('electron-log');
// Basic buffering workflow
log.buffering.begin();
// These messages will be buffered, not immediately logged
log.info('Starting operation');
log.debug('Step 1 completed');
log.debug('Step 2 completed');
// Decide whether to commit or reject based on outcome
if (operationSucceeded) {
log.buffering.commit(); // All buffered messages are now logged
} else {
log.buffering.reject(); // Discard all buffered messages
}
// Conditional logging based on results
function performComplexOperation() {
log.buffering.begin();
log.debug('Initializing complex operation');
try {
const result = doComplexWork();
log.debug('Complex work completed successfully', result);
if (result.shouldLog) {
log.buffering.commit(); // Log debug info on success
} else {
log.buffering.reject(); // Skip debug info for normal operations
}
return result;
} catch (error) {
log.error('Complex operation failed:', error);
log.buffering.commit(); // Always log debug info on errors
throw error;
}
}
// Check buffering state
if (log.buffering.enabled) {
console.log('Currently buffering', log.buffering.buffer.length, 'messages');
}
// Batch logging for performance
function batchedLogging() {
log.buffering.begin();
// Generate many log messages
for (let i = 0; i < 1000; i++) {
log.debug(`Processing item ${i}`);
}
// Process all at once for better performance
log.buffering.commit();
}Template variables for message formatting and path resolution.
interface Variables {
processType: string;
[name: string]: any;
}Usage Examples:
const log = require('electron-log');
// Set custom variables
log.variables.userId = 'user123';
log.variables.sessionId = 'session456';
log.variables.buildNumber = '1.0.1-beta';
// Use in custom format
log.transports.console.format = '[{processType}] [{userId}] {text}';
log.transports.file.format = '{y}-{m}-{d} {h}:{i}:{s} [{buildNumber}] [{level}] {text}';
// Access in hooks
log.hooks.push((message) => {
if (log.variables.environment === 'development') {
return { ...message, data: ['[DEV]', ...message.data] };
}
return message;
});Environment-specific initialization for different process types.
interface MainLogger extends Logger {
/**
* Initialize the logger to be available in renderer process
* @param options - Initialization options
*/
initialize(options?: {
getSessions?: () => object[];
includeFutureSessions?: boolean;
preload?: string | boolean;
spyRendererConsole?: boolean;
}): void;
}Usage Examples:
// Main process
const log = require('electron-log/main');
// Basic initialization
log.initialize();
// Advanced initialization
log.initialize({
preload: true, // Install preload script automatically
spyRendererConsole: true, // Capture renderer console messages
getSessions: () => [session.defaultSession], // Custom session handling
includeFutureSessions: true // Handle dynamically created sessions
});Comprehensive logger setup with custom transport factories and error handling.
class Logger {
constructor(options?: {
allowUnknownLevel?: boolean;
dependencies?: object;
errorHandler?: ErrorHandler;
eventLogger?: EventLogger;
initializeFn?: () => void;
isDev?: boolean;
levels?: string[];
logId?: string;
transportFactories?: { [key: string]: () => Transport };
variables?: Variables;
});
}Usage Examples:
const { Logger } = require('electron-log');
// Create logger with custom configuration
const customLogger = new Logger({
levels: ['critical', 'error', 'warn', 'info', 'trace'],
logId: 'custom-app',
allowUnknownLevel: true,
variables: {
processType: 'worker',
workerId: process.pid
},
transportFactories: {
console: () => customConsoleTransport,
database: () => customDatabaseTransport
}
});
// Add custom levels
customLogger.addLevel('security', 1); // Between critical and error
customLogger.addLevel('performance', 4); // Between info and trace
// Use custom logger
customLogger.critical('System critical error');
customLogger.security('Security violation detected');
customLogger.performance('Operation took 150ms');Access and manage multiple logger instances.
class Logger {
static instances: { [logId: string]: Logger };
/**
* Get existing logger instance by ID
* @param options - Logger identification
* @returns Existing logger instance or creates new one
*/
static getInstance(options: { logId?: string }): Logger;
}Usage Examples:
const { Logger } = require('electron-log');
// Access existing instances
const defaultLogger = Logger.getInstance({ logId: 'default' });
const authLogger = Logger.getInstance({ logId: 'auth' });
// List all active instances
console.log('Active loggers:', Object.keys(Logger.instances));
// Cleanup instances
delete Logger.instances['old-logger'];interface Logger extends LogFunctions {
logId: string;
levels: string[];
transports: { [key: string]: Transport | null };
variables: Variables;
hooks: Hook[];
functions: LogFunctions;
buffering: Buffering;
errorHandler: ErrorHandler;
scope: Scope;
addLevel(level: string, index?: number): void;
create(options: { logId: string }): Logger;
processMessage(message: LogMessage, options?: { transports?: Transport[] | string[] }): void;
}
interface MainLogger extends Logger {
initialize(options?: {
getSessions?: () => object[];
includeFutureSessions?: boolean;
preload?: string | boolean;
spyRendererConsole?: boolean;
}): void;
errorHandler: ErrorHandler<MainErrorHandlerOptions>;
eventLogger: EventLogger;
transports: MainTransports;
}
interface RendererLogger extends Logger {
errorHandler: ErrorHandler<RendererErrorHandlerOptions>;
transports: RendererTransports;
}
interface NodeLogger extends Logger {
errorHandler: ErrorHandler<MainErrorHandlerOptions>;
eventLogger: EventLogger;
transports: MainTransports;
}
interface Variables {
processType: string;
[name: string]: any;
}
interface Buffering {
buffer: LogMessage[];
enabled: boolean;
begin(): void;
commit(): void;
reject(): void;
}
type Hook = (
message: LogMessage,
transport?: Transport,
transportName?: string,
) => LogMessage | false;