1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| const express = require('express'); const morgan = require('morgan'); const path = require('path'); const winston = require('winston'); const DailyRotateFile = require('winston-daily-rotate-file');
const app = express(); const logDirectory = path.join(__dirname, 'logs');
const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.json() ), transports: [ new winston.transports.Console({ format: winston.format.combine( winston.format.colorize(), winston.format.simple() ) }), new DailyRotateFile({ filename: path.join(logDirectory, 'application-%DATE%.log'), datePattern: 'YYYY-MM-DD', zippedArchive: true, maxSize: '20m', maxFiles: '14d' }), new winston.transports.File({ filename: path.join(logDirectory, 'error.log'), level: 'error' }) ] });
app.use(morgan('combined', { stream: { write: (message) => logger.info(message.trim()) } }));
app.use((err, req, res, next) => { logger.error({ url: req.url, method: req.method, error: err.message, stack: err.stack }); res.status(500).json({ code: 500, message: 'Internal Server Error' }); });
|