all files / lib/plugins/ redis_handler.js

36% Statements 9/25
0% Branches 0/18
0% Functions 0/4
36% Lines 9/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                                                                                       
'use strict';
 
const Redis = require('ioredis');
const pp = require('plugin-party');
const _ = require('lodash');
 
/**
 * A handler that relays log events to pubsub channel in redis.
 *
 * @class RedisHandler
 * @extends Plugin
 */
const RedisHandler = pp.plugin({
  type: 'handler',
  name: 'redis',
  configure: function (options, ctx) {
    this.options = _.extend(this.options, options || {});
    if(this.options.redis) {
      this.redis = this.options.redis instanceof Redis ? this.options.redis : new Redis(this.options.redis);
    } else {
      this.redis = new Redis();
    }
    this.channel = this.options.channel || this.getDefaultChannel();
    if(ctx) {
      this.bind(ctx);
    }
    return this;
  }
});
 
const proto = RedisHandler.prototype;
 
proto.bind = function (ctx) {
  if(!this._handler) {
    this._handler = this.handleLogEvent.bind(this);
    ctx.on('log', this._handler);
  }
  return this;
};
 
proto.handleLogEvent = function (event) {
  this.redis.publish(this.channel, JSON.stringify(event));
};
 
proto.getDefaultChannel = function () {
  const appName = process.title || process.env.APP_NAME || process.env.APP || 'unnamed';
  const env = process.env.NODE_ENV || 'development';
  return ['catlog', 'message', env, appName].join(':');
};
 
 
module.exports = RedisHandler;