diff --git a/lib/bunyan.js b/lib/bunyan.js index 04d70d5..9e5b30f 100644 --- a/lib/bunyan.js +++ b/lib/bunyan.js @@ -84,6 +84,7 @@ if (runtimeEnv === 'browser') { var util = require('util'); var assert = require('assert'); var EventEmitter = require('events').EventEmitter; +var stream = require('stream'); try { 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 @@ -568,6 +576,9 @@ Logger.prototype.addStream = function addStream(s, defaultLevel) { switch (s.type) { case 'stream': + assert.ok(isWritable(s.stream), + '"stream" stream is not writable: ' + util.inspect(s.stream)); + if (!s.closeOnExit) { s.closeOnExit = false; } diff --git a/test/add-stream.test.js b/test/add-stream.test.js new file mode 100644 index 0000000..757274f --- /dev/null +++ b/test/add-stream.test.js @@ -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(); +});