Last active
December 14, 2015 16:08
-
-
Save Jimbly/5112692 to your computer and use it in GitHub Desktop.
Logging to zlib log stream with periodic flushing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var assert = require('assert'); | |
var zlib = require('zlib'); | |
var gzip = zlib.createGzip(); | |
var fs = require('fs'); | |
var FILENAME = 'log.txt.gz'; | |
var out = fs.createWriteStream(FILENAME); | |
gzip.pipe(out); | |
function debug(msg) { | |
console.log((new Date()).toISOString() + ' DEBUG> ' + msg); | |
} | |
var needs_flush = false; | |
var is_flushing = false; | |
var FLUSH_DELAY = 2000; | |
function doFlush() { | |
needs_flush = false; | |
debug('caling flush'); | |
gzip.flush(function() { | |
debug('flush finished'); | |
is_flushing = false; | |
if (needs_flush) { | |
is_flushing = true; | |
setTimeout(doFlush, FLUSH_DELAY); | |
} | |
}); | |
} | |
function writeLine(data) { | |
debug('calling write'); | |
gzip.write((new Date()).toISOString() + ' ' + data + '\n', function() { | |
debug('write finished'); | |
}); | |
needs_flush = true; | |
if (!is_flushing) { | |
is_flushing = true; | |
setTimeout(doFlush, FLUSH_DELAY); | |
} | |
} | |
setInterval(function() { | |
// write some data | |
writeLine('A line of data'); | |
}, 500); | |
var last_size = 0; | |
setInterval(function() { | |
fs.stat('log.txt.gz', function(err, stats) { | |
console.log('File size at ' + stats.size); | |
assert(stats.size > last_size); | |
last_size = stats.size; | |
}); | |
}, 5000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This works on older versions of node (0.6.21), but throws an internal assertion on node 0.9.21