Redirecting stdout to file nodejs

前端 未结 5 1657
情歌与酒
情歌与酒 2020-12-29 06:12

I\'ve created:

var access = fs.createWriteStream(\'/var/log/node/api.access.log\', { flags: \'w\' });

Then piped:

process.s         


        
5条回答
  •  旧巷少年郎
    2020-12-29 06:39

    Originally based on @Anatol-user3173842 answer

    But in my case I needed to hook the stdout & stderr and also write into a file.

    So for those who need to keep the normal stdout behaviour in addition to writing into the file. Use the following.

    For non-errors:

    // stdout logging hook
    const stdoutWrite0 = process.stdout.write;
    process.stdout.write = (args) => { // On stdout write
      CustomLogger.writeToLogFile('log', args); // Write to local log file
      args = Array.isArray(args) ? args : [args]; // Pass only as array to prevent internal TypeError for arguments
      return stdoutWrite0.apply(process.stdout, args);
    };
    

    For errors:

    // stderr logging hook
    const stderrWrite0 = process.stderr.write;
    process.stderr.write = (args) => { // On stderr write
      CustomLogger.writeToLogFile('error', args); // Write to local error file
      args = Array.isArray(args) ? args : [args]; // Pass only as array to prevent internal TypeError for arguments
      return stderrWrite0.apply(process.stderr, args);
    };
    
    // uncaught exceptions
    process.on('uncaughtException', (err) => {
      CustomLogger.writeToLogFile('error', ((err && err.stack) ? err.stack : err));
    });
    

    Here is the CustomLogger code, where I also separate the log files by date:

    export class CustomLogger {
    
     static LOGS_DIR = 'location-of-my-log-files';
    
     private static logDailyName(prefix: string): string {
       const date = new Date().toLocaleDateString().replace(/\//g, '_');
       return `${CustomLogger.LOGS_DIR}/${prefix}_${date}.log`;
     }
    
     private static writeToLogFile(prefix, originalMsg) {
       const timestamp   = Date.now();
       const fileName    = this.logDailyName(prefix);
       const logMsg      = prepareForLogFile(originalMsg);
       fs.appendFileSync(fileName, `${timestamp}\t${logMsg}\n\n`);
       return originalMsg;
     }
    }
    

提交回复
热议问题