我是否可以配置console.log,以便将日志写入文件,而不是打印在控制台中?
当前回答
我经常使用很多参数console.log()和console.error(),所以我的解决方案是:
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;
其他回答
您现在可以使用Caterpillar,这是一个基于流的日志记录系统,允许您登录它,然后将输出输出到不同的转换和位置。
输出到一个文件很简单:
var logger = new (require('./').Logger)();
logger.pipe(require('fs').createWriteStream('./debug.log'));
logger.log('your log message');
卡特彼勒网站上的完整示例
我只是建立了一个包来做这个,希望你喜欢它;) https://www.npmjs.com/package/writelog
如果您正在使用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
Rudy Huynh的解决方案对我来说非常有效。我添加了一点,让它吐出带有今天日期和时间的文件。
var dateNow = new Date();
var timeNow = dateNow.getHours() + '-' + dateNow.getMinutes();
var logPath = "log/" + dateNow.toDateString() + ' -' + ' Start Time - ' + timeNow + ".log"
consoleLogToFile({
logFilePath: logPath
});
它不是很优雅,但这样它将保存不同的,易于阅读的日志文件,而不是只是更新相同的“default.log”文件。
我自己简单地从温斯顿的例子,并添加了log(…)方法(因为温斯顿命名为info(..):
Console.js:
"use strict"
// Include the logger module
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
// Add log command
logger.log=logger.info;
module.exports = logger;
然后在代码中使用:
const console = require('Console')
现在你可以简单地在你的文件中使用正常的日志功能,它会创建一个文件并将其记录到你的控制台(在调试/开发时)。因为if (process.env。NODE_ENV !== 'production'){(如果你想让它也在生产环境中)…
推荐文章
- 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包设置自定义位置?