我是否可以配置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
推荐文章
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在Ubuntu上安装Node.js
- 使用express.js代理
- Python日志记录不输出任何东西
- Node -使用NODE_MODULE_VERSION 51根据不同的Node.js版本编译
- RabbitMQ / AMQP:单队列,同一消息的多个消费者?
- IE9是否支持console.log,它是一个真实的功能吗?
- Node.js同步执行系统命令
- 禁用包的postinstall脚本
- Node.js上的html解析器
- 错误:无法找到模块“webpack”
- 有nginx access_log和error_log日志的STDOUT和STDERR的主进程
- 在node.js中使用async / await文件系统
- NodeJS -用NPM安装错误
- 如何为本地安装npm包设置自定义位置?