我是否可以配置console.log,以便将日志写入文件,而不是打印在控制台中?
当前回答
如果你正在寻找生产中的东西,温斯顿可能是最好的选择。
如果你只是想快速完成开发工作,直接输出到文件中(我认为这只适用于*nix系统):
nohup node simple-server.js > output.log &
其他回答
如果您正在寻找不修改任何代码的解决方案,这里有一个简单的解决方案。
它需要pm2,只需将它添加到你的节点模块,并启动你的应用程序
pm2 start server.js
你完成了,控制台。日志现在自动注册在home/.pm2/ Logs /server-out.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.
除了上面的答案之外,还对覆盖console.log的简短而有效的代码进行了一点扩展。小增加:设置文件名与日期,包装功能,也做原来的控制台。日志记录以保持控制台使用该信息处于活动状态。
用法:在代码的开头,运行setConsoleLogToFile([FILENAME])。
const fs = require("fs"),
util = require('util');
const getPrettyDate = ()=> new Date().toString().replace(":","-").replace(/00\s\(.*\)/, "").replace(` ${new Date().getFullYear()}`, ",").replace(/:\d\d\s/, " ");
module.exports.getPrettyDate = getPrettyDate;
module.exports.setConsoleLogToFile = (filename) => {
const log_file = fs.createWriteStream(`${__dirname}/${filename} - ${getPrettyDate()}.log`, { flags: 'w' }),
log_stdout = process.stdout;
const origConsole = console.log;
console.log = (d) => {
origConsole(d);
log_file.write(util.format(d) + '\n');
log_stdout.write(util.format(d) + '\n');
};
}
你可以使用nodejs的Console构造函数
const mylog = new console.Console(
fs.createWriteStream("log/logger.log"),
fs.createWriteStream("log/error.log")
);
然后你就可以像使用普通的控制台类一样使用它了,例如:
mylog.log("Ok!"); // Will be written into 'log/logger.log'
mylog.error("Bad!"); // Will be written into 'log/error.log'
重写console.log是正确的方法。但是要让它在所需的模块中工作,还需要导出它。
module.exports = console;
为了节省自己写日志文件的麻烦,旋转和东西,你可以考虑使用一个简单的记录器模块,如温斯顿:
// Include the logger module
var winston = require('winston');
// Set up log file. (you can also define size, rotation etc.)
winston.add(winston.transports.File, { filename: 'somefile.log' });
// Overwrite some of the build-in console functions
console.error = winston.error;
console.log = winston.info;
console.info = winston.info;
console.debug = winston.debug;
console.warn = winston.warn;
module.exports = console;
推荐文章
- 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包设置自定义位置?