我是否可以配置console.log,以便将日志写入文件,而不是打印在控制台中?


当前回答

直接来自控制台的nodejs API文档

const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
const count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5

其他回答

如果您正在使用linux,您还可以使用输出重定向。Windows就不太确定了。

node server.js >> file.log 2>> file.log

>> file.log将标准输出重定向到文件

2>> file.log将stderr重定向到文件

其他人使用速记&>>作为stdout和stderr,但它不被我的MAC和ubuntu接受:(

额外:>覆盖,>>追加。

顺便说一下,关于NodeJS日志记录器,我使用pino + pino-pretty logger

如果你正在寻找生产中的东西,温斯顿可能是最好的选择。

如果你只是想快速完成开发工作,直接输出到文件中(我认为这只适用于*nix系统):

nohup node simple-server.js > output.log &

大多数记录器是过量的,不支持console.log中的正确构建。因此我创建了console-log-to-file:

import { consoleLogToFile } from "console-log-to-file";
// or `const { consoleLogToFile } = require("console-log-to-file/dist/index.cjs.js")`

consoleLogToFile({
  logFilePath: "/log/default.log",
});

// all of your console.log/warn/error/info will work as it does and save to file now.

如果这是针对应用程序的,那么最好使用日志记录模块。这会给你更多的灵活性。一些建议。

·温斯顿https://github.com/winstonjs/winston log4js https://github.com/nomiddlename/log4js-node

我只是建立了一个包来做这个,希望你喜欢它;) https://www.npmjs.com/package/writelog