|
| 1 | +#!/usr/bin/env node |
| 2 | +/* BEGIN JSSTYLED */ |
| 3 | +/** |
| 4 | + * <https://github.com/trentm/node-bunyan/pull/473> is a change to add a |
| 5 | + * feature to Bunyan's log record stringification to log `undefined` values. |
| 6 | + * Let's attempt that with a custom raw stream. |
| 7 | + * |
| 8 | + * Note that a raw stream here isn't ideal, because using a custom raw stream |
| 9 | + * means that it is a pain to use some of the other built-in stream types |
| 10 | + * (file, rotating-file). However, it might be a satisfactory workaround for |
| 11 | + * some. |
| 12 | + * |
| 13 | + * Example: |
| 14 | + * $ node log-undefined-values.js |
| 15 | + * {"name":"log-undefined-values","hostname":"danger0.local","pid":28161,"level":30,"anull":null,"aundef":"[Undefined]","anum":42,"astr":"foo","msg":"hi","time":"2017-03-04T20:53:54.331Z","v":0} |
| 16 | + * $ node log-undefined-values.js | bunyan |
| 17 | + * [2017-03-04T20:54:41.874Z] INFO: log-undefined-values/28194 on danger0.local: hi (anull=null, aundef=[Undefined], anum=42, astr=foo) |
| 18 | + */ |
| 19 | +/* END JSSTYLED */ |
| 20 | + |
| 21 | +var bunyan = require('../lib/bunyan'); |
| 22 | +var fs = require('fs'); |
| 23 | + |
| 24 | + |
| 25 | +function replacer() { |
| 26 | + // Note: If node > 0.10, then could use Set here (see `safeCyclesSet()` |
| 27 | + // in bunyan.js) for a performance improvement. |
| 28 | + var seen = []; |
| 29 | + return function (key, val) { |
| 30 | + if (val === undefined) { |
| 31 | + return '[Undefined]'; |
| 32 | + } else if (!val || typeof (val) !== 'object') { |
| 33 | + return val; |
| 34 | + } |
| 35 | + if (seen.indexOf(val) !== -1) { |
| 36 | + return '[Circular]'; |
| 37 | + } |
| 38 | + seen.push(val); |
| 39 | + return val; |
| 40 | + }; |
| 41 | +} |
| 42 | + |
| 43 | +function LogUndefinedValuesStream(stream) { |
| 44 | + this.stream = stream; |
| 45 | +} |
| 46 | +LogUndefinedValuesStream.prototype.write = function (rec) { |
| 47 | + var str = JSON.stringify(rec, replacer()) + '\n'; |
| 48 | + this.stream.write(str); |
| 49 | +} |
| 50 | + |
| 51 | +var log = bunyan.createLogger({ |
| 52 | + name: 'log-undefined-values', |
| 53 | + streams: [ { |
| 54 | + level: 'info', |
| 55 | + type: 'raw', |
| 56 | + stream: new LogUndefinedValuesStream(process.stdout) |
| 57 | + } ] |
| 58 | +}); |
| 59 | + |
| 60 | +log.info({anull: null, aundef: undefined, anum: 42, astr: 'foo'}, 'hi'); |
0 commit comments