我正在使用Node.js,我想创建一个获取所有控制台日志的函数(使用console.log(message)
)。
如何获取所有控制台日志并将其写入文件(不是覆盖)?
答案 0 :(得分:0)
对于nodejs库,npm repo是您的朋友 - 您可以找到很多并尝试最适合您需求的内容。例如https://www.npmjs.com/package/log首先搜索log
。{/ p>
当然,您也可以通过使用自己的函数覆盖控制台函数来实现自己的挂钩到控制台,例如:
var fs = require('fs');
function myLog(file) {
return function() {
fs.appendFileSync(file || 'log.txt', arguments.join('\n'));
}
}
console.log = myLog();
console.warn = myLog();
console.error = myLog('errorLog.txt');
答案 1 :(得分:0)
<强> logger.js 强>
var fs = require('fs');
var log = [];
//override default console.log behaviour
console.log = function(d) {
process.stdout.write(d + '\n');
log.push(d); //intercept every log and keep the value
};
//log to file
function log(filePath, clb){
clb = clb || function(){}; //optional callback
fs.truncate(filePath, 0, function() {
fs.writeFile(filePath, string, function (err) {
clb(err)
});
});
}
module.exports = log;
然后在您的代码中导入文件并在需要时调用该函数。
var logger = require('./logger');
logger.log('log.txt', function(err){
if(err)
console.log(err);
//else ok
});
答案 2 :(得分:0)
一种简单的方法是使用记录数据的函数覆盖控制台上的log
函数,并写入文件系统。
以下是一般概念:
function attachFSLogger(filePath) {
// remember the old log method
const oldLog = console.log; // remove this line if you only want to log into the file
// override console.log
console.log = (...messages) => {
// log the console message immediately as usual
oldLog.apply(console, messages); // remove this line if you only want to log into the file
// asynchronously append to the file log
fs.appendFile(filePath, messages.join('\n'), (err) => {
if (err) throw err;
});
}
}
attachFSLogger('./logs.txt');
console.log('test'); // logs 'test' and also appends 'test' to logs.txt
如果您希望经常记录内容,则使用流将更多efficient:
function attachFSLogger(filePath) {
// remember the old log method
const oldLog = console.log; // remove this line if you only want to log into the file
// create a write stream for the given file path
const fsLog = fs.createWriteStream(filePath, {
flags: 'a' // 'a' means appending
})
// override console.log
console.log = (...messages) => {
// log the console message immediately as usual
oldLog.apply(console, messages); // remove this line if you only want to log into the file
// stream message to the file log
fsLog.write(messages.join('\n'));
}
}
attachFSLogger('./logs.txt');
console.log('test'); // logs 'test' and also appends 'test' to logs.txt
话虽如此,有很多图书馆可以为您做这样的事情并且已经过全面测试。
这是一对夫妇: