Skip to content

Commit

Permalink
Added buffer option to logger
Browse files Browse the repository at this point in the history
Improves performance greatly, however to
retain the information that could be potentially
lost we may want to do some signal trapping and
error handling to ensure logs are written to
the stream
  • Loading branch information
tj committed Aug 11, 2010
1 parent f8f1320 commit 7613464
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 2 deletions.
6 changes: 6 additions & 0 deletions docs/logger.md
Expand Up @@ -6,6 +6,12 @@ The _logger_ middleware provides common log format support, as well as custom fo
connect.logger(),
);

The logger also has built in buffering support to increase performance. When the `buffer` option is set to `true` it defaults to 1000 milliseconds, however you can specify your own duration. When using the `buffer` option log lines are not written to the stream immediately, they are buffered in an array, and flushed periodically.

connect.createServer(
connect.logger({ buffer: 2000 })
);

A custom format can also be passed:

connect.createServer(
Expand Down
2 changes: 1 addition & 1 deletion examples/router/app.js
Expand Up @@ -58,7 +58,7 @@ function main(app){
var connect = require('./../../lib/connect');

var server = connect.createServer(
connect.logger()
connect.logger({ buffer: true })
);

server.use("/users/", connect.router(user));
Expand Down
35 changes: 34 additions & 1 deletion lib/connect/middleware/logger.js
Expand Up @@ -5,13 +5,30 @@
* MIT Licensed
*/

/**
* Log buffer.
*
* @type Array
*/

var buf = [];

/**
* Default log buffer duration.
*
* @type Number
*/

var defaultBufferDuration = 1000;

/**
* Log requests with the given `options`.
*
* Options:
*
* - `format` Format string, see below for tokens
* - `stream` Output stream, defaults to _stdout_
* - `buffer` Buffer duration, defaults to 1000ms when _true_
*
* Tokens:
*
Expand All @@ -35,7 +52,23 @@ module.exports = function logger(options) {
options = options || {};

var fmt = process.connectEnv.logFormat || options.format,
stream = options.stream || process.stdout;
realStream = stream = options.stream || process.stdout,
buffer = options.buffer;

// Buffering support
if (buffer) {
setInterval(function(){
if (buf.length) {
realStream.write(buf.join(''), 'ascii');
buf.length = 0;
}
}, typeof buffer === 'number' ? buffer : defaultBufferDuration);
stream = {
write: function(str){
buf.push(str);
}
};
}

return function logger(req, res, next) {
var start = +new Date,
Expand Down

0 comments on commit 7613464

Please sign in to comment.