Ensure stream for type='stream' stream is a writable stream :)

Fixes #332
This commit is contained in:
Michael Nisi 2016-02-20 08:58:37 +01:00 committed by Trent Mick
parent d9c5970be2
commit cf1926fef6
2 changed files with 50 additions and 0 deletions

View file

@ -84,6 +84,7 @@ if (runtimeEnv === 'browser') {
var util = require('util'); var util = require('util');
var assert = require('assert'); var assert = require('assert');
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var stream = require('stream');
try { try {
var safeJsonStringify = require('safe-json-stringify'); var safeJsonStringify = require('safe-json-stringify');
@ -303,6 +304,13 @@ function resolveLevel(nameOrNum) {
} }
function isWritable(obj) {
if (obj instanceof stream.Writable) {
return true;
}
return typeof (obj.write) === 'function';
}
//---- Logger class //---- Logger class
@ -568,6 +576,9 @@ Logger.prototype.addStream = function addStream(s, defaultLevel) {
switch (s.type) { switch (s.type) {
case 'stream': case 'stream':
assert.ok(isWritable(s.stream),
'"stream" stream is not writable: ' + util.inspect(s.stream));
if (!s.closeOnExit) { if (!s.closeOnExit) {
s.closeOnExit = false; s.closeOnExit = false;
} }

39
test/add-stream.test.js Normal file
View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2016 Trent Mick. All rights reserved.
*
* Test stream adding.
*/
var bunyan = require('../lib/bunyan');
// node-tap API
if (require.cache[__dirname + '/tap4nodeunit.js'])
delete require.cache[__dirname + '/tap4nodeunit.js'];
var tap4nodeunit = require('./tap4nodeunit.js');
var test = tap4nodeunit.test;
test('non-writables passed as stream', function (t) {
var things = ['process.stdout', {}];
things.forEach(function (thing) {
function createLogger() {
bunyan.createLogger({
name: 'foo',
stream: thing
});
}
t.throws(createLogger,
/stream is not writable/,
'"stream" stream is not writable');
})
t.end();
});
test('proper stream', function (t) {
var log = bunyan.createLogger({
name: 'foo',
stream: process.stdout
});
t.ok('should not throw');
t.end();
});