问题描述
我在 NodeJS 服务器上使用 PM2,我在 package.json
文件中有一些 npm 命令,它们在生产或开发模式下调用 pm2,如下所示:
"scripts": {
"dev": "env NODE_ENVIRONMENT=development pm2-dev start ecosystem.config.js --ignore 'data'","production": "env NODE_ENVIRONMENT=production pm2 start ecosystem.config.js"
}
调用这些命令时,ecosystem.config.js
文件分别在生产和开发环境中使用节点解释器或 ts-node 解释器。
const { mkdirsync } = require('fs');
var script = "";
var exec_interpreter = "";
var err_log = "";
var out_log = "";
var combined_log = "";
var date = new Date().toISOString();
if (process.env.NODE_ENVIRONMENT === 'production') {
script = "dist/app.js";
exec_interpreter = "node";
mkdirsync(`./logs/${date}`,{ recursive: true },(err) => {
if (!err) {
err_log = './logs/' + date + '/error.log';
out_log = './logs/' + date + '/output.log';
combined_log = './logs/' + date + '/combined.log';
} else { console.error(err),process.exit(1) };
});
}
if (process.env.NODE_ENVIRONMENT === 'development') {
script = "src/app.ts";
exec_interpreter = "ts-node";
}
module.exports = {
apps: [{
name: 'Hyve',script: script,exec_interpreter: exec_interpreter,max_restarts: 10,error_file: err_log,out_file: out_log,log_file: combined_log,time: true
}]
}
如您所见,日志也被定向到生产环境中的日志文件。但是,当脚本在生产环境中运行时,日志文件不会按照我的意图进入单独的文件夹,而是将它们写入日志文件夹的根目录中。这将有助于形象化我的意思:
预期结果:
logs
├── 2021-05-30T06:56:31.477Z
│ ├── combined.log
│ ├── error.log
│ └── output.log
└── 2021-05-30T06:56:56.512Z
├── combined.log
├── error.log
└── output.log
实际结果:
logs
├── 2021-05-30T06:56:31.477Z
├── 2021-05-30T06:56:56.512Z
├── combined.log
├── error.log
└── output.log
我该如何解决这个问题?
解决方法
var date = new Date();
var dat= date.getDate()+"-"+date.getMonth()+"-"+date.getFullYear();
fs.mkdirSync(`./logs/${dat}`,{ recursive: true });
fs.exists("./logs/${dat}",(err) => {
if (!err) {
console.log('in');
err_log = './logs/' + date.toISOString() + '/error.log';
out_log = './logs/' + date.toISOString() + '/output.log';
combined_log = './logs/' + date.toISOString() + '/combined.log';
} else {
console.error(err)};
console.log("created succesfully");
});
在这里,我将主文件夹与日期和日志文件与 ISOString 分开,这也将帮助您花时间。