-
-
Save gillesdemey/71d9d02108e469320deaa1251c5f2ecf to your computer and use it in GitHub Desktop.
var pino = require('./') | |
var RingBuffer = require('./ringbuffer') | |
var rb = new RingBuffer({ limit: 10 }) | |
var log = pino(rb) | |
setInterval(() => { | |
log.info(new Date()) | |
}, 5) | |
setTimeout(() => { | |
console.log(rb.getRecords()) | |
process.exit(0) | |
}, 100) |
'use strict' | |
var stream = require('stream') | |
var util = require('util') | |
function RingBuffer (options) { | |
var self = this | |
self.limit = options && options.limit ? options.limit : 100 | |
self.records = [] | |
stream.Writable.call(this) | |
} | |
util.inherits(RingBuffer, stream.Writable) | |
RingBuffer.prototype.write = function (record) { | |
if (this.records.length >= this.limit) this.records.pop() | |
this.records.push(record) | |
} | |
RingBuffer.prototype.getRecords = function () { | |
return this.records.map((record) => record.replace(/\n$/, '')) | |
} | |
module.exports = RingBuffer |
Also this won't be compatible with extreme mode, or rather it will but each "record" will be 4kb of logs...
I can see two ways to handle this:
- Put a caveat in readme - done.
- Check the size of the first line that's written. If it's around 4kb either throw or warn about extreme mode - of course this could trigger for a really large single record, but if the size of a record is that big there should probably be a warning about options.limit * logsize anyway
Also this won't be compatible with extreme mode
I came to the exact same conclusion, hence I didn't enable extreme mode in the example.
Thanks a bunch for your other comments — it's rare to find good constructive feedback with regards to performance in javascript / node. I'll surely include them in the next iteration and separate this into its own module.
Yah cool then we'll add to readme, one other thing - would encourage exporting a function that returns a new instance of RingBuffer rather than exporting the constructor directly. This avoids issues that arise from forgetting new, naming convention stuff, fp paradigm friendly, generally makes for quicker api grocking imo
this.records = new Array(options.limit)
.map
and replace ingetRecords
is expensive, why not just join to a string and leave the newlines since that's the log format anyway? Or if there's a compelling reason, a for loop (particularly for in) and substring would be significantly faster