Nodejs
[Nodejs] Nodemon으로 오류 기록하고 자동 재시작하기
teamnova
2024. 1. 18. 12:00
728x90
Nodejs으로 서버 실행 중에 에러가 날 때, 예외처리가 되어있지 않다면 서버가 멈춰버립니다. 하지만 아래 코드를 활용하면 어떤 원인으로 서버가 멈췄는지 error.log를 통해 확인 가능하고, 지속적인 서버 운영도 가능합니다.
nodemon.json
{
"restartable": "rs",
"events": {
"crash": "nodemon --delay 500ms"
}
}
package.json
{
"name": "your-project-name",
"version": "1.0.0",
"scripts": {
"start": "nodemon app.js"
},
"dependencies": {
"express": "^4.17.1",
"moment-timezone": "^0.5.33",
"winston": "^3.3.3"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
app.js
const winston = require('winston');
const moment = require('moment-timezone');
const timeStampFormat = winston.format((info, opts) => {
info.timestamp = moment().tz('Asia/Seoul').format();
return info;
});
const logger = winston.createLogger({
level: 'error',
format: winston.format.combine(
timeStampFormat(),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: 'error.log' })
]
});
process.on('uncaughtException', (error) => {
logger.error({ message: 'Unhandled Exception', error });
});
process.on('unhandledRejection', (error) => {
logger.error({ message: 'Unhandled Rejection', error });
});
setInterval(() => {
// This will create an uncaught exception
throw new Error('Intentional Error for testing');
}, 5000);