简体   繁体   English

txt 文件中的 Node.js console.log()

[英]Node.js console.log() in txt file

I have another question ( last question ).我还有一个问题( 最后一个问题)。 At the moment i am working on a Node.js project and in this I have many console.log() functions.目前我正在处理一个 Node.js 项目,在这个项目中我有很多console.log() 函数。 This has worked okay so far but I also want everything that's written to the console to also be written in a log-file.到目前为止,这一切正常,但我也希望写入控制台的所有内容写入日志文件。 Can someone please help me?有人可以帮帮我吗?

For example:例如:

Console.log('The value of array position [5] is '+ array[5]);

In my real code its a bit more but this should give you an idea.在我的真实代码中它有点多,但这应该给你一个想法。

Thank you hopefully.谢谢希望。

Just run the script in your terminal like this...只需像这样在终端中运行脚本...

node script-file.js > log-file.txt

This tells the shell to write the standard output of the command node script-file.js to your log file instead of the default, which is printing it to the console.这告诉 shell 将命令node script-file.js的标准输出写入您的日志文件,而不是将其打印到控制台的默认值。

This is called redirection and its very powerful.这称为重定向,它非常强大。 Say you wanted to write all errors to a separate file...假设您想将所有错误写入一个单独的文件...

node script-file.js >log-file.txt 2>error-file.txt

Now all console.log are written to log-file.txt and all console.error are written to error-file.txt现在所有console.log都写入log-file.txt ,所有console.error写入error-file.txt

I would use a library instead of re-inventing the wheel.我会使用图书馆而不是重新发明轮子。 I looked for a log4j -type library on npm, and it came up with https://github.com/nomiddlename/log4js-node我在 npm 上寻找了一个log4j类型的库,它想出了https://github.com/nomiddlename/log4js-node

if you want to log to the console and to a file:如果要登录到控制台和文件:

var log4js = require('log4js');
log4js.configure({
  appenders: [
    { type: 'console' },
    { type: 'file', filename: 'logs/cheese.log', category: 'cheese' }
  ]
});

now your code can create a new logger with现在您的代码可以创建一个新的记录器

var logger = log4js.getLogger('cheese'); 

and use the logger in your code并在您的代码中使用记录器

logger.warn('Cheese is quite smelly.');
logger.info('Cheese is Gouda.');
logger.debug('Cheese is not a food.');

You could try overriding the built in console.log to do something different.您可以尝试覆盖内置的console.log来做一些不同的事情。

var originalLog = console.log;

console.log = function(str){
  originalLog(str);
  // Your extra code
}

However, this places the originalLog into the main scope, so you should try wrapping it in a function.但是,这会将originalLog放入主作用域,因此您应该尝试将其包装在函数中。 This is called a closure, and you can read more about them here .这称为闭包,您可以 在此处阅读有关它们的更多信息。

(function(){
   var originalLog = console.log;

  console.log = function(str){
  originalLog(str);
  // Your extra code
})();

To write files, see this stackoverflow question, and to override console.log even better than the way I showed, see this .要写入文件,请参阅stackoverflow 问题,并以比我展示的方式更好地覆盖console.log ,请参阅 Combining these two answers will get you the best possible solution.结合这两个答案将为您提供最佳解决方案。

const fs = require('fs');
const myConsole = new console.Console(fs.createWriteStream('./output.txt'));
myConsole.log('hello world');

This will create an output file with all the output which can been triggered through console.log('hello world') inside the console.这将创建一个输出文件,其中包含可以通过console.log('hello world')内的console.log('hello world')触发的所有输出。

This is the easiest way to convert the console.log() output into a text file.`这是将console.log()输出转换为文本文件的最简单方法。`

@activedecay's answer seems the way to go. @activedecay 的答案似乎是要走的路。 However, as of april 30th 2018 , I have had trouble with that specific model (node crashed due to the structure of the object passed on to .configure , which seems not to work in the latest version).但是,截至april 30th 2018 ,我遇到了该特定模型的问题(由于传递给.configure的对象结构,节点崩溃,这在最新版本中似乎不起作用)。 In spite of that, I've managed to work around an updated solution thanks to nodejs debugging messages...尽管如此,由于nodejs调试消息,我已经设法解决了更新的解决方案......

const myLoggers = require('log4js');

myLoggers.configure({
    appenders: { mylogger: { type:"file", filename: "path_to_file/filename" } },
    categories: { default: { appenders:["mylogger"], level:"ALL" } }
});
const logger = myLoggers.getLogger("default");

Now if you want to log to said file, you can do it just like activedecay showed you:现在,如果您想登录到所述文件,您可以像activedecay向您展示的那样进行操作

logger.warn('Cheese is quite smelly.');
logger.info('Cheese is Gouda.');
logger.debug('Cheese is not a food.');

This however, will not log anything to the console, and since I haven't figured out how to implement multiple appenders in one logger, you can still implement the good old console.log();但是,这不会将任何内容记录到控制台,而且由于我还没有弄清楚如何在一个记录器中实现多个 appender,您仍然可以实现旧的console.log();

PD: I know that this is a somewhat old thread, and that OP's particular problem was already solved, but since I came here for the same purpose, I may as well leave my experience so as to help anyone visiting this thread in the future PD:我知道这是一个有点旧的线程,OP的特定问题已经解决了,但既然我是为了同样的目的来到这里,我不妨留下我的经验,以帮助将来访问此线程的任何人

Just write your own log function:只需编写自己的日志函数:

function log(message) {
   console.log(message);
   fs.writeFileSync(...);
}

Then replace all your existing calls to console.log() with log() .然后用log()替换所有现有的对console.log()调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM