UNPKG

energy-manager-iot

Version:

Library for energy management in IoT devices via MQTT protocol. Documentation: https://jonhvmp.github.io/energy-manager-iot-docs/

241 lines (240 loc) 7.69 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const winston_1 = __importDefault(require("winston")); const path_1 = __importDefault(require("path")); const fs_1 = __importDefault(require("fs")); /** * Custom log levels with numeric priorities * Lower numbers represent higher priority levels */ const levels = { error: 0, warn: 1, info: 2, http: 3, debug: 4, trace: 5 }; // Set log level based on environment const level = process.env.LOG_LEVEL || (process.env.NODE_ENV === 'production' ? 'info' : 'debug'); // Create logs directory if it doesn't exist const logDir = 'logs'; if (!fs_1.default.existsSync(logDir)) { fs_1.default.mkdirSync(logDir); } /** * Custom formatter that intelligently formats objects and arrays */ const smartFormat = winston_1.default.format((info) => { const args = info.args || []; // Process each argument for better formatting if (args && Array.isArray(args) && args.length > 0) { info.metadata = info.metadata || {}; // TypeScript workaround to access arbitrary properties const metadata = info.metadata; metadata.details = args.map((arg) => { if (arg instanceof Error) { return { errorMessage: arg.message, stack: arg.stack, ...(Object.getOwnPropertyNames(arg).reduce((obj, key) => { obj[key] = arg[key]; return obj; }, {})) }; } return arg; }); } return info; }); /** * Log formatting configuration for console output */ const consoleFormat = winston_1.default.format.combine(winston_1.default.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }), winston_1.default.format.colorize({ all: false }), winston_1.default.format.padLevels(), winston_1.default.format.printf((info) => { const { timestamp, level, message } = info; const module = info.module; const correlationId = info.correlationId; let logMessage = `${timestamp} [${level}]`; if (module) { logMessage += ` [${module}]`; } if (correlationId) { logMessage += ` [${correlationId}]`; } logMessage += `: ${message}`; // Add metadata if present const metadata = info.metadata; if (metadata && Object.keys(metadata).length > 0) { if (metadata.details && Array.isArray(metadata.details)) { // Format each detailed item on new line const detailsText = metadata.details .map((detail) => typeof detail === 'object' ? JSON.stringify(detail, null, 2) : String(detail)) .join('\n '); if (detailsText.trim()) { logMessage += `\n ${detailsText}`; } } else { // General metadata logMessage += ` ${JSON.stringify(metadata)}`; } } return logMessage; })); /** * Log formatting configuration for file output (JSON for machine processing) */ const fileFormat = winston_1.default.format.combine(winston_1.default.format.timestamp(), smartFormat(), winston_1.default.format.errors({ stack: true }), winston_1.default.format.json()); /** * Log transport configurations for different environments */ const transports = [ // Console transport for all environments new winston_1.default.transports.Console({ format: consoleFormat, handleExceptions: true }), // File transports for all environments new winston_1.default.transports.File({ filename: path_1.default.join(logDir, 'error.log'), level: 'error', format: fileFormat, maxsize: 10485760, // 10MB maxFiles: 5, handleExceptions: true }), new winston_1.default.transports.File({ filename: path_1.default.join(logDir, 'combined.log'), format: fileFormat, maxsize: 10485760, // 10MB maxFiles: 5 }) ]; // Create logger instance with Winston const winstonLogger = winston_1.default.createLogger({ level, levels, defaultMeta: { service: 'energy-manager' }, transports, exitOnError: false }); /** * Enhanced professional logger with contextual information support */ class EnhancedLogger { correlationId; module; /** * Creates a new logger instance with optional context * * @param module - Name of the module using this logger * @param correlationId - Optional correlation ID for tracking related log entries */ constructor(module, correlationId) { this.module = module; this.correlationId = correlationId; } /** * Creates a child logger with additional context * * @param module - Name of the module using this logger * @param correlationId - Optional correlation ID for tracking related log entries * @returns A new logger instance with the specified context */ child(module, correlationId) { return new EnhancedLogger(module || this.module, correlationId || this.correlationId); } /** * Sets a correlation ID for tracking related log entries * * @param id - Correlation ID to use for subsequent logs * @returns This logger instance for method chaining */ withCorrelationId(id) { this.correlationId = id; return this; } /** * Log error message with stack trace support * * @param msg - Primary message to log * @param args - Additional data or error objects to include */ error(msg, ...args) { winstonLogger.error(msg, { module: this.module, correlationId: this.correlationId, args }); } /** * Log warning message * * @param msg - Primary message to log * @param args - Additional data to include in the log */ warn(msg, ...args) { winstonLogger.warn(msg, { module: this.module, correlationId: this.correlationId, args }); } /** * Log informational message * * @param msg - Primary message to log * @param args - Additional data to include in the log */ info(msg, ...args) { winstonLogger.info(msg, { module: this.module, correlationId: this.correlationId, args }); } /** * Log debug message for development troubleshooting * * @param msg - Primary message to log * @param args - Additional data to include in the log */ debug(msg, ...args) { winstonLogger.debug(msg, { module: this.module, correlationId: this.correlationId, args }); } /** * Log detailed trace message for deep troubleshooting * * @param msg - Primary message to log * @param args - Additional data to include in the log */ trace(msg, ...args) { winstonLogger.log('trace', msg, { module: this.module, correlationId: this.correlationId, args }); } /** * Log HTTP communication for API troubleshooting * * @param msg - Primary message to log * @param args - Additional data to include in the log */ http(msg, ...args) { winstonLogger.http(msg, { module: this.module, correlationId: this.correlationId, args }); } } exports.default = new EnhancedLogger('core');