2

I know it's a very abstract question, but I just don't know where/how to start.

I am using bunyan as a logging library in my app. This is a sample syntax for logging something:

 const log = bunyan.createLogger({...});
 log.info(...);
 log.error(...);

I want to create some kind of a wrapper so that every time log.<something>() is called, it will execute the functionality from my module. Specifically, I want to do a curl request with the object produced by log.<something>().

I was looking into messina and gelf-stream which are wrappers around bunyan but I didn't really spot any specific code that handles logging events or anything that will give me an example of how to accomplish my idea.

I was thinking of adding event emitters to bunyan that I can listen for in my module, but that would require me to my fork of the lib, and I don't wanna do that. So, now I'm out of ideas.

4

1 回答 1

3

您可以通过创建可写流来扩展 bunyan 的功能:

const bunyan = require( "bunyan" ),
      stream = require( "stream" );

class MyStream extends stream.Writable {

    /**
     * When we have a record from bunyan
     */
    write( record ) {
            console.log( "-----> ", record );
            return true;
    }

}

/** Options for the bunyan instance */
const options = {
    name : "my-logger",
    serializers : bunyan.stdSerializers,
    level : "trace",
    streams : [
            { type : "stream", stream : process.stdout, level : "trace" },
            { type : "raw", stream : new MyStream(), level : "trace" }
    ]
};

/** Create the bunyan logger */
const log = bunyan.createLogger( options );

log.info( { foo: "bar" }, "test" );

这将输出:

{"name":"my-logger","hostname":"localhost","pid":68694,"level":30,"foo":"bar","msg":"test","time":"2017-08-11T11:31:40.136Z","v":0}
----->  { name: 'my-logger',
  hostname: 'localhost',
  pid: 68694,
  level: 30,
  foo: 'bar',
  msg: 'test',
  time: 2017-08-11T11:31:40.136Z,
  v: 0 }

您可以用您想到的任何方法替换write( record ) { ... }方法代码,处理日志行本身。

您还可以在bunyan 文档中阅读有关流的更多信息

于 2017-08-11T11:34:20.717 回答