2

I'm using bunyan.js as my logging solution and I would like to add functionality to it's logging functions.

For example I would like to send something to a third party API each time there's a call to log.fatal()

Is that possible? I looked through the docs and I didn't see any events I can register to, or any other solution.

Thanks!

Tzvika Mordoch
  • 191
  • 2
  • 13
  • There are quite a lot of Bunyan stream plugins for logging to external services, perhaps you can check out how those are implemented ([start here](https://www.npmjs.com/search?q=bunyan)). – robertklep May 30 '16 at 13:50
  • Thanks, but I didn't find any that would help me (my goal is sending alerts to datadog) – Tzvika Mordoch May 30 '16 at 13:53
  • 1
    But you can check their source, how they implement adding logging functionality to Bunyan. It should be fairly easy, as Bunyan works with streams, so you could implement a stream class that would push log messages to Datadog. – robertklep May 30 '16 at 14:20

1 Answers1

4

Bunyan has it's "streams": https://github.com/trentm/node-bunyan#streams Every logger can write to multiple streams.

You can either specify additional streams while creating logger object, or use addStream method (it is not mentioned in their readme, but it's a public method, that logger uses internally too), for example:

logger.addStream({
    type: 'raw',
    stream: new MyDatadog(),
    closeOnExit: true,
    // Here you specify what level should be written to this stream.
    // For example, you can use soemthing like `logger.FATAL` here.
    level: options.level
});

And then:

function MyDatadog () {
    // initialize whatever is needed here
}

MyDatadog.prototype.write = function write (record) {
    // write record data wherever you want
    // record is an object with things like:
    // - record.what
    // - record.time
    // - record.err
};

MyDatadog.prototype.end = function end () {
    // cleanup stuff here
};

Of course, creating own wrapper is not needed if whatever you use (some datadog library?) gives you writable stream which accepts writing JS objects.

ahwayakchih
  • 2,101
  • 19
  • 24
  • Thats great! I can implement MyDatadog as ES6 class no? Also, what does closeOnExit determine? – Tzvika Mordoch May 31 '16 at 08:21
  • Check their source for more info: https://github.com/trentm/node-bunyan/blob/cbfaa9a7bd86c658dbb8333c894191d23b65be33/lib/bunyan.js#L331 and https://github.com/trentm/node-bunyan/blob/cbfaa9a7bd86c658dbb8333c894191d23b65be33/lib/bunyan.js#L544 - if true, bunyan should automatically close your stream, but i'm not sure it actually does that. – ahwayakchih May 31 '16 at 09:29