【问题标题】:How to write logs in file in NodeJS (Linux)? [duplicate]如何在 NodeJS(Linux)中写入日志? [复制]
【发布时间】:2020-01-08 15:01:59
【问题描述】:

我的简单脚本(test.js):

const x = 10;
console.log('Number X = ' + x);
throw new Error('emulating some error in the code');
console.log('Finish');

例如我用命令开始我的脚本: node test.js >> log.txt

我只能在控制台中看到错误消息。错误未写入 log.txt

如何在 log.txt 中写入错误信息?

【问题讨论】:

  • 如果你只是想在shell中重定向输出,试试node test.js >> log.txt 2>&1 这样你就将stderr重定向到stdout

标签: node.js linux debian


【解决方案1】:

这一定正是您正在寻找的:

// First part: Writing to 'log.txt' file
var fs = require('fs');
var util = require('util');
var logFile = fs.createWriteStream('log.txt', { flags: 'a' });
  // Or 'w' to truncate the file every time the process starts.
var logStdout = process.stdout;

console.log = function () {
  logFile.write(util.format.apply(null, arguments) + '\n');
  logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;

// Second part: creating function just to generate an error
function div (x, y, done) {
  if (y === 0)
    return done (Error ('Cannot divide by zero'))
  else
    return done (null, x / y)
}

div (6, 0, function (err, result) {
  // *always* check for err
  if (err)
    console.log ('error', err.message, err.stack)
  else
    console.log ('result', result)
})

代码的第一部分用于写入“log.txt”文件,第二部分仅用于生成错误。希望这会有所帮助:)

【讨论】:

  • Kyle Jonkol,我更新了我的答案。请看一下:)
  • 谢谢你的回答,但这方法太难了,我希望你使用 linux 的默认工具 - 带有 >> log.txt
猜你喜欢
  • 1970-01-01
  • 2014-10-07
  • 1970-01-01
  • 2021-04-26
  • 1970-01-01
  • 1970-01-01
  • 2015-08-27
  • 2016-08-02
  • 1970-01-01
相关资源
最近更新 更多