Node.js console.log() in txt file

后端 未结 6 488
耶瑟儿~
耶瑟儿~ 2020-12-24 03:29

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. This has worked ok

相关标签:
6条回答
  • 2020-12-24 03:58

    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.

    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

    0 讨论(0)
  • 2020-12-24 03:58

    @activedecay's answer seems the way to go. 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). In spite of that, I've managed to work around an updated solution thanks to nodejs debugging messages...

    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:

    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();

    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

    0 讨论(0)
  • 2020-12-24 04:01

    You could try overriding the built in console.log to do something different.

    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. 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. Combining these two answers will get you the best possible solution.

    0 讨论(0)
  • 2020-12-24 04:01

    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().

    0 讨论(0)
  • 2020-12-24 04:02
    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.

    This is the easiest way to convert the console.log() output into a text file.`

    0 讨论(0)
  • 2020-12-24 04:13

    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

    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.');
    
    0 讨论(0)
提交回复
热议问题