/**
* Logger utility for structured logging across the MCP WPPConnect Server.
* Provides methods for error, warning, info, and debug logging with context.
*/
type LogLevel = 'error' | 'warn' | 'info' | 'debug';
interface LogEntry {
timestamp: string;
level: LogLevel;
context: string;
message: string;
data?: unknown;
}
/**
* Safely convert unknown error to string
*/
function errorToString(error: unknown): string {
if (error instanceof Error) return error.message;
if (typeof error === 'string') return error;
if (error && typeof error === 'object' && 'message' in error) return String(error.message);
return String(error);
}
class Logger {
private readonly debugMode: boolean;
constructor(debugMode: boolean = process.env.DEBUG?.includes('mcp-wppconnect') ?? false) {
this.debugMode = debugMode;
}
private formatLog(entry: LogEntry): string {
const { timestamp, level, context, message, data } = entry;
let output = `[${timestamp}] [${level.toUpperCase()}] [${context}] ${message}`;
if (data && this.debugMode) {
output += ` ${JSON.stringify(data, null, 2)}`;
}
return output;
}
error(context: string, error: unknown): void {
const message = errorToString(error);
const data = error instanceof Error ? { stack: error.stack } : undefined;
const entry: LogEntry = {
timestamp: new Date().toISOString(),
level: 'error',
context,
message,
data,
};
console.error(this.formatLog(entry));
}
warn(context: string, message: string): void {
const entry: LogEntry = {
timestamp: new Date().toISOString(),
level: 'warn',
context,
message,
};
console.warn(this.formatLog(entry));
}
info(context: string, message: string, data?: unknown): void {
const entry: LogEntry = {
timestamp: new Date().toISOString(),
level: 'info',
context,
message,
data,
};
console.log(this.formatLog(entry));
}
debug(context: string, message: string, data?: unknown): void {
if (this.debugMode) {
const entry: LogEntry = {
timestamp: new Date().toISOString(),
level: 'debug',
context,
message,
data,
};
console.log(this.formatLog(entry));
}
}
}
export const logger = new Logger();