1

How can make every time the program is launched, that the logs are overwritten into a new file? And so that the end of the file name was the date and time of the file creation.

var fs  = require('fs');

var ws = fs.createWriteStream('test.log', { 
    'flags'   : 'w',
    'encoding': 'utf8',
    'mode'    : 0666,
});

process.stdout.wr = process.stdout.write;
process.stdout.er = process.stderr.write;

process.stdout.write = function(mes, c) {
    ws.write(mes + '\r\n');
    process.stdout.wr(mes, c)   
};

process.stderr.write = function(mes, c) {
    ws.write(mes + '\r\n');
    process.stdout.er(mes, c)   
};
lifeisfoo
  • 12,017
  • 4
  • 59
  • 102

1 Answers1

3

You can do it using a code like this:

const date = new Date();
const timestamp = date.getTime();

var ws = fs.createWriteStream(`test-${timestamp}.log`, { 
    'flags'   : 'w',
    'encoding': 'utf8',
    'mode'    : 0666,
});

Log filenames will be something like test-1553591263787.log, test-1553591318028.log...

If you want a custom date/time format, check this SO question about formatting.

lifeisfoo
  • 12,017
  • 4
  • 59
  • 102