Skip to content

Instantly share code, notes, and snippets.

@suprememoocow
Last active May 11, 2019 01:19
Show Gist options
  • Save suprememoocow/5133080 to your computer and use it in GitHub Desktop.
Save suprememoocow/5133080 to your computer and use it in GitHub Desktop.
A function for reopening a winston File logging transport post logrotation on a HUP signal. To send a HUP to your node service, use the postrotate configuration option from logrotate. `postrotate kill -HUP ‘cat /var/run/mynodeservice.pid‘`
function reopenTransportOnHupSignal(fileTransport) {
process.on('SIGHUP', function() {
var fullname = path.join(fileTransport.dirname, fileTransport._getFile(false));
function reopen() {
if (fileTransport._stream) {
fileTransport._stream.end();
fileTransport._stream.destroySoon();
}
var stream = fs.createWriteStream(fullname, fileTransport.options);
stream.setMaxListeners(Infinity);
fileTransport._size = 0;
fileTransport._stream = stream;
fileTransport.once('flush', function () {
fileTransport.opening = false;
fileTransport.emit('open', fullname);
});
fileTransport.flush();
}
fs.stat(fullname, function (err) {
if (err && err.code == 'ENOENT') {
return reopen();
}
});
});
}
@jonrahoi
Copy link

thanks for this. I'm having a hard time grasping where to reliably get the pid when i'm using a keep-alive package like forever or pm2 - any ideas?

Copy link

ghost commented Apr 30, 2014

You could use pm2's JSON output, @jonrahoi - pm2 jlist; you'll have to find the relevant app yourself.

Copy link

ghost commented Apr 30, 2014

Even better: pm2 sendSignal SIGHUP my-app ...

@graywithanA
Copy link

Have you considered using copytruncate instead of executing kill -HUP... in postrotate. copytruncate will copy the current log file to the rotated file and then truncate the original log file to 0 bytes. This allows node to keep writing to the same stream.

@blongstreth
Copy link

I would avoid using logrotatecopytruncate if you are worried about logging log data. Per the logrotate docs:

copytruncate
Truncate the original log file in place after creating a copy,
instead of moving the old log file and optionally creating a new
one, It can be used when some program can not be told to close
its logfile and thus might continue writing (appending) to the
previous log file forever. Note that there is a very small time
slice between copying the file and truncating it, so some log-
ging data might be lost. When this option is used, the create
option will have no effect, as the old log file stays in place.

@robsongajunior
Copy link

robsongajunior commented May 3, 2019

please, can you show who is fileTransport param?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment