8

I'm using WinstonJS for logging to a file, and nodemon to restart when I update my code.

var winston = require('winston');

var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.File)({
            level: 'silly',
            filename: __dirname + '/logs/test.log',
            json: false
        })
    ]
});

logger.log('info', 'something');

The log file is being appended to, however when I make a code change and save my file, nodemon runs it again and the log file is appended to again. This leads to a log file that just keeps getting longer and longer, and I have to keep manually deleting the contents.

I guess I could do something with the fs module, but it would be far nicer to use Winston to say something like update: replace|append, but I can't see anything like that available.

Is there any way to clear the log file, so I only have log entries for the last time my code was run..?

Stephen Last
  • 5,491
  • 9
  • 44
  • 85
  • I've found this: https://github.com/winstonjs/winston/blob/master/examples/create-file.js, which uses `fs` to delete the file before recreating it again. Seems a bit over the top to me though. – Stephen Last Dec 16 '15 at 16:43

2 Answers2

15

The

{ flags: 'w' }

property on the options object on the new transport is working for me:

  transports: [
    new winston.transports.File({ filename: 'myLog.txt', options: { flags: 'w' } })
  ]
MattG
  • 5,589
  • 5
  • 36
  • 52
6

I know this question is a little outdated, but I recently found the answer to this and thought I would share it here for posterity. You can pass fs.createWriteStream options to the File logger:

// Open the file in "write" mode, which truncates first
options: { flags: 'w' },
Chad Robinson
  • 4,575
  • 22
  • 27