我正在尝试将 HTTP 请求记录到 .log
文件中。
我像这样创建和编写它。
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'logger.log'), { flags: 'a' });
我通过中间件写入它。
app.use((req, res, next) => {
const start = process.hrtime()
res.on('finish', () => {
const durationInMilliseconds = getDurationInMilliseconds (start); accessLogStream.write(`${req.method}\t\t${req.originalUrl}\t\t${res.statusCode}\t\t${Math.trunc(durationInMilliseconds).toLocaleString()}ms\n`)
})
next()
})
点击 /logs
端点时,我读取文件中的数据
app.get('/api/v1/on-covid-19/logs?',(req,res) => {
fs.readFile('./logger.log', 'utf8', function(err, data) {
if (err) throw err;
// line by line
res.format({
'text/plain': function () {
res.send(data)}})
})
});
上述功能能够写入 devt 中的 logger.log
文件,但不会更新 heroku
上生产环境中的 logger.log
文件>。我没做什么?
点击 /logs
端点会在生产中返回一个空的 data
字符串。
最佳答案
Heroku Dynos 使用 Ephemeral Filesystem ,这是一个读/写文件系统,仅在 Dyno 运行时可用,一旦 Dyno 重新启动或停止(至少每 24 小时发生一次),写入文件系统的任何更改都会被摧毁。当启动新的 Dyno 时,Dyno 将具有与部署期间构建应用程序时编译的文件系统相同的文件系统。
对于您的应用程序日志,强烈建议您使用 logging addon在专用服务中流式传输和存储日志。如果您必须将日志存储为文件,则需要使用大容量存储系统,例如 AWS S3。
关于javascript - Node Js 在生产中不写入日志文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61188862/