syia-mcp-utils
Version:
Global utility functions for MCP server
70 lines (69 loc) • 2.99 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.logger = void 0;
const winston_1 = __importDefault(require("winston"));
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
// Ensure logs directory exists with error handling
let logsDir;
let canWriteLogs = false;
try {
logsDir = path_1.default.join(process.cwd(), 'logs');
if (!fs_1.default.existsSync(logsDir)) {
fs_1.default.mkdirSync(logsDir, { recursive: true });
}
canWriteLogs = true;
}
catch (error) {
console.warn('Could not create logs directory, file logging will be disabled:', error);
canWriteLogs = false;
}
// Determine environment
const NODE_ENV = process.env.NODE_ENV || 'development';
const isProd = NODE_ENV === 'production';
// Configure log level based on environment
const logLevel = isProd ? 'info' : process.env.LOG_LEVEL || 'debug';
// Custom format for production (structured JSON logs)
const productionFormat = winston_1.default.format.combine(winston_1.default.format.timestamp(), winston_1.default.format.errors({ stack: true }), winston_1.default.format.json());
// Custom format for development (colorized and readable)
const developmentFormat = winston_1.default.format.combine(winston_1.default.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston_1.default.format.errors({ stack: true }), winston_1.default.format.colorize(), winston_1.default.format.printf(({ level, message, timestamp, ...meta }) => {
const metaString = Object.keys(meta).length ? JSON.stringify(meta, null, 2) : '';
return `${timestamp} [${level}]: ${message} ${metaString}`;
}));
// Create transports array
const transports = [
// Console transport (always available)
new winston_1.default.transports.Console({
format: developmentFormat
})
];
// Add file transports only if we can write to logs directory
if (canWriteLogs) {
transports.push(new winston_1.default.transports.File({
filename: 'logs/error.log',
level: 'error',
silent: !isProd && process.env.ENABLE_FILE_LOGGING !== 'true'
}), new winston_1.default.transports.File({
filename: 'logs/combined.log',
silent: !isProd && process.env.ENABLE_FILE_LOGGING !== 'true'
}));
}
// Create exception handlers
const exceptionHandlers = [
new winston_1.default.transports.Console({ format: developmentFormat })
];
if (canWriteLogs) {
exceptionHandlers.unshift(new winston_1.default.transports.File({ filename: 'logs/exceptions.log' }));
}
// Create and export the logger
exports.logger = winston_1.default.createLogger({
level: logLevel,
format: isProd ? productionFormat : developmentFormat,
defaultMeta: { service: 'purchase-mcp-server', environment: NODE_ENV },
transports,
exceptionHandlers,
exitOnError: false
});