const winston = require('winston'); // Define log format const logFormat = winston.format.combine( winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.errors({ stack: true }), winston.format.json(), winston.format.prettyPrint() ); // Create logs directory if it doesn't exist (before creating logger) const fs = require('fs'); const path = require('path'); const logsDir = path.join(process.cwd(), 'logs'); let useFileLogging = true; try { if (!fs.existsSync(logsDir)) { fs.mkdirSync(logsDir, { recursive: true }); } } catch (error) { console.warn('Cannot create logs directory, using console logging only:', error.message); useFileLogging = false; } // Create transports array const transports = []; // Add file transports only if we can write to filesystem if (useFileLogging) { try { transports.push( new winston.transports.File({ filename: 'logs/error.log', level: 'error', maxsize: 5242880, // 5MB maxFiles: 5, tailable: true }), new winston.transports.File({ filename: 'logs/combined.log', maxsize: 5242880, // 5MB maxFiles: 5, tailable: true }) ); } catch (error) { console.warn('Cannot create file transports, using console logging only:', error.message); useFileLogging = false; } } // Always add console logging in production if file logging fails if (!useFileLogging || process.env.NODE_ENV === 'production') { transports.push(new winston.transports.Console({ format: winston.format.combine( winston.format.colorize(), winston.format.simple(), winston.format.printf(({ timestamp, level, message, ...meta }) => { return `${timestamp} [${level}]: ${message} ${ Object.keys(meta).length ? JSON.stringify(meta, null, 2) : '' }`; }) ) })); } // Create the logger const logger = winston.createLogger({ level: process.env.LOG_LEVEL || 'info', format: logFormat, defaultMeta: { service: 'uga-chatbot' }, transports: transports, }); module.exports = logger;