All files / logzio-nodejs/lib logzio-nodejs.js

95% Statements 152/160
81.4% Branches 70/86
95.65% Functions 22/23
94.97% Lines 151/159

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 2941x 1x 1x 1x 1x   1x   1x 20x       20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x   20x         20x 20x     20x   20x 4x               20x         20x     20x   20x 20x 20x     1x 20x 20x 20x     1x 127x 127x           1x 2x         1x 1x 1x 1x 1x   1x 1x       1x 21x 1x 1x     21x 21x 1x       1x 6x 6x   6x 1x 1x 1x       6x   10x 10x 10x   10x 10x       1x   19x     19x 3x 3x     19x 3x       19x                 1x 136x 136x   136x 1x 1x       1x 137x 1x   136x 12x       136x 136x 135x   136x   136x 136x 18x 18x       1x   23x 6x 6x   17x 17x 17x     23x     1x 17x   17x 17x 17x 17x   17x     1x 18x 18x 127x   18x     1x 75x     1x 18x 18x                       18x 1x 1x 1x 1x       1x       18x 2x   18x     1x 18x 18x     1x 1x 1x       18x 18x 18x   1x 1x     1x 1x 1x 1x 1x           17x 17x 1x   16x 16x              
var request = require('request');
var stringifySafe = require('json-stringify-safe');
var _assign = require('lodash.assign');
var dgram = require('dgram');
var zlib = require('zlib');
 
exports.version = require('../package.json').version;
 
var LogzioLogger = function (options) {
    Iif (!options || !options.token) {
        throw new Error('You are required to supply a token for logging.');
    }
 
    this.token = options.token;
    this.host = options.host || 'listener.logz.io';
    this.userAgent = 'Logzio-Logger NodeJS';
    this.type = options.type || 'nodejs';
    this.sendIntervalMs = options.sendIntervalMs || 10 * 1000;
    this.bufferSize = options.bufferSize || 100;
    this.debug = options.debug || false;
    this.numberOfRetries = options.numberOfRetries || 3;
    this.timer = null;
    this.closed = false;
    this.supressErrors = options.supressErrors || false;
    this.addTimestampWithNanoSecs = options.addTimestampWithNanoSecs || false;
    this.doCompress = options.doCompress || false;
 
    var protocolToPortMap = {
        'udp': 5050,
        'http': 8070,
        'https': 8071
    };
    this.protocol = options.protocol || 'http';
    Iif (!protocolToPortMap.hasOwnProperty(this.protocol)) {
        throw new Error('Invalid protocol defined. Valid options are : ' + JSON.stringify(Object.keys(protocolToPortMap)));
    }
    this.port = options.port || protocolToPortMap[this.protocol];
 
    if (this.protocol === 'udp') {
        this.udpClient = dgram.createSocket('udp4');
    }
 
    /*
      Callback method executed on each bulk of messages sent to logzio.
      If the bulk failed, it will be called: callback(exception), otherwise upon
      success it will called as callback()
    */
    this.callback = options.callback || this._defaultCallback;
 
    /*
     * the read/write/connection timeout in milliseconds of the outgoing HTTP request
     */
    this.timeout = options.timeout;
 
    // build the url for logging
    this.url = this.protocol + '://' + this.host + ':' + this.port + '?token=' + this.token;
 
    this.messages = [];
    this.bulkId = 1;
    this.extraFields = options.extraFields || {};
};
 
exports.createLogger = function (options) {
    var l = new LogzioLogger(options);
    l._timerSend();
    return l;
};
 
var jsonToString = exports.jsonToString = function (json) {
    try {
        return JSON.stringify(json);
    } catch (ex) {
        return stringifySafe(json, null, null, function () {});
    }
};
 
LogzioLogger.prototype._defaultCallback = function (err) {
    Iif (err && !this.supressErrors) {
        console.error('logzio-logger error: ' + err, err);
    }
};
 
LogzioLogger.prototype.sendAndClose = function (callback) {
    this.callback = callback || this._defaultCallback;
    this._debug('Sending last messages and closing...');
    this._popMsgsAndSend();
    clearTimeout(this.timer);
 
    Eif (this.protocol === 'udp') {
        this.udpClient.close();
    }
};
 
LogzioLogger.prototype._timerSend = function () {
    if (this.messages.length > 0) {
        this._debug('Woke up and saw ' + this.messages.length + ' messages to send. Sending now...');
        this._popMsgsAndSend();
    }
 
    var self = this;
    this.timer = setTimeout(function () {
        self._timerSend();
    }, this.sendIntervalMs);
};
 
LogzioLogger.prototype._sendMessagesUDP = function () {
    var messagesLength = this.messages.length;
    var self = this;
 
    var udpSentCallback = function (err, bytes) {
        Eif (err) {
            self._debug('Error while sending udp packets. err = ' + err);
            self.callback(new Error('Failed to send udp log message. err = ' + err));
        }
    };
 
    for (var i = 0; i < messagesLength; i++) {
 
        var msg = this.messages[i];
        msg.token = this.token;
        var buff = new Buffer(stringifySafe(msg));
 
        self._debug('Starting to send messages via udp.');
        this.udpClient.send(buff, 0, buff.length, this.port, this.host, udpSentCallback);
    }
};
 
LogzioLogger.prototype.close = function () {
    // clearing the timer allows the node event loop to quit when needed
    clearTimeout(this.timer);
 
    // send pending messages, if any
    if (this.messages.length > 0) {
        this._debug('Closing, purging messages.');
        this._popMsgsAndSend();
    }
 
    if (this.protocol === 'udp') {
        this.udpClient.close();
    }
 
    // no more logging allowed
    this.closed = true;
};
 
/**
 * Attach a timestamp to the log record. If @timestamp already exists, use it. Else, use current time.
 * The same goes for @timestamp_nano
 * @param msg - The message (Object) to append the timestamp to.
 * @private
 */
LogzioLogger.prototype._addTimestamp = function (msg) {
    var now = (new Date()).toISOString();
    msg['@timestamp'] = msg['@timestamp'] || now;
 
    if (this.addTimestampWithNanoSecs) {
        var time = process.hrtime();
        msg['@timestamp_nano'] = msg['@timestamp_nano'] || [now, time[0].toString(), time[1].toString()].join('-');
    }
};
 
LogzioLogger.prototype.log = function (msg) {
    if (this.closed === true) {
        throw new Error('Logging into a logger that has been closed!');
    }
    if (typeof msg === 'string') {
        msg = {
            message: msg
        };
    }
    msg = _assign(msg, this.extraFields);
    if (!msg.type) {
        msg.type = this.type;
    }
    this._addTimestamp(msg);
 
    this.messages.push(msg);
    if (this.messages.length >= this.bufferSize) {
        this._debug('Buffer is full - sending bulk');
        this._popMsgsAndSend();
    }
};
 
LogzioLogger.prototype._popMsgsAndSend = function () {
 
    if (this.protocol === 'udp') {
        this._debug('Sending messages via udp');
        this._sendMessagesUDP();
    } else {
        var bulk = this._createBulk(this.messages);
        this._debug('Sending bulk #' + bulk.id);
        this._send(bulk);
    }
 
    this.messages = [];
};
 
LogzioLogger.prototype._createBulk = function (msgs) {
    var bulk = {};
    // creates a new copy of the array. Objects references are copied (no deep copy)
    bulk.msgs = msgs.slice();
    bulk.attemptNumber = 1;
    bulk.sleepUntilNextRetry = 2 * 1000;
    bulk.id = this.bulkId++;
 
    return bulk;
};
 
LogzioLogger.prototype._messagesToBody = function (msgs) {
    var body = '';
    for (var i = 0; i < msgs.length; i++) {
        body = body + jsonToString(msgs[i]) + '\n';
    }
    return body;
};
 
LogzioLogger.prototype._debug = function (msg) {
    Eif (this.debug) console.log('logzio-nodejs: ' + msg);
};
 
LogzioLogger.prototype._send = function (bulk) {
    var body = this._messagesToBody(bulk.msgs);
    var options = {
        body: body,
        uri: this.url,
        headers: {
            'host': this.host,
            'accept': '*/*',
            'user-agent': this.userAgent,
            'content-type': 'text/plain',
            'content-length': Buffer.byteLength(body)
        }
    };
 
    if (this.doCompress) {
        options.headers['content-encoding'] = 'gzip';
        zlib.gzip(body, function (err, result) {
            Eif (!err)
                options.body = result;
            else {
                this._debug('Failed to use gzip compression. Using uncompress body');
            }
            console.log(options.body);
        });
    }
 
    if (typeof this.timeout !== 'undefined') {
        options.timeout = this.timeout;
    }
    this._tryToSend(options, bulk);
};
 
LogzioLogger.prototype._tryToSend = function (options, bulk) {
    var callback = this.callback;
    var self = this;
 
    function tryAgainIn(sleepTimeMs) {
        self._debug('Bulk #' + bulk.id + ' - Trying again in ' + sleepTimeMs + '[ms], attempt no. ' + bulk.attemptNumber);
        setTimeout(function () {
            self._send(bulk);
        }, sleepTimeMs);
    }
 
    try {
        request.post(options, function (err, res, body) {
            if (err) {
                // In rare cases server is busy
                Eif (err.code === 'ETIMEDOUT' || err.code === 'ECONNRESET' || err.code === 'ESOCKETTIMEDOUT' || err.code === 'ECONNABORTED') {
                    Iif (bulk.attemptNumber >= self.numberOfRetries) {
                        callback(new Error('Failed after ' + bulk.attemptNumber + ' retries on error = ' + err, err));
                    } else {
                        self._debug('Bulk #' + bulk.id + ' - failed on error: ' + err);
                        var sleepTimeMs = bulk.sleepUntilNextRetry;
                        bulk.sleepUntilNextRetry = bulk.sleepUntilNextRetry * 2;
                        bulk.attemptNumber++;
                        tryAgainIn(sleepTimeMs);
                    }
                } else {
                    callback(err);
                }
            } else {
                var responseCode = res.statusCode.toString();
                if (responseCode !== '200') {
                    callback(new Error('There was a problem with the request.\nResponse: ' + responseCode + ': ' + body.toString()));
                } else {
                    self._debug('Bulk #' + bulk.id + ' - sent successfully');
                    callback();
                }
            }
        });
    } catch (ex) {
        callback(ex);
    }
};