Esempio n. 1
0
var calculateRange = function _calculateRange(t, opts) {
  out.trace('calcRange called with: ' + typeof t + ' ' + t + (opts ? ' and options: ' + stringify(opts) : ''));
  var sep = opts && opts.separator ? opts.separator.toUpperCase() : '/';
  var ret = {};

  // first check whether it's a datetime range
  var sepAt = ('' + t).indexOf(sep);

  if (sepAt > -1) {  // it looks like range
    ret = parseRange(t, sepAt, sep);

  } else {           // it appears to be a single entry (date-time or duration)

    if (isDuration(t)) {
      var duration = applyDuration(moment(), t);  // now - duration
      out.trace('parse: found a standalone duration which yielded date-time: ' + duration.toISOString());

      ret.start = duration.toDate();

    } else {

      // then it should be just a regular ISO-8601 datetime?
      // try 'human time' if that also fails
      var d = parseTime(t);
      if (d && d.isValid()) {
        ret.start = d.toDate();
      } else {
        // not a range, not a duration, not a date-time, jeez!
        throw new Error('Unable to interpret -t parameter. Open up help ' +
            'with \'logsene search --help\' to see usage info and examples');
      }
    }
  }
  return ret;
};
Esempio n. 2
0
Logger.prototype._emit = function (rec, noemit) {
    var i;

    // Lazily determine if this Logger has non-'raw' streams. If there are
    // any, then we need to stringify the log record.
    if (this.haveNonRawStreams === undefined) {
        this.haveNonRawStreams = false;
        for (i = 0; i < this.streams.length; i++) {
            if (!this.streams[i].raw) {
                this.haveNonRawStreams = true;
                break;
            }
        }
    }

    // Stringify the object. Attempt to warn/recover on error.
    var str;
    if (noemit || this.haveNonRawStreams) {
        if (this.customStringify) {
            str = this.customStringify(rec);
        } else {
            try {
                str = JSON.stringify(rec, safeCycles()) + '\n';
            } catch (e) {
                if (safeJsonStringify) {
                    str = safeJsonStringify(rec) + '\n';
                } else {
                    var dedupKey = e.stack.split(/\n/g, 2).join('\n');
                    _warn('bunyan: ERROR: Exception in '
                        + '`JSON.stringify(rec)`. You can install the '
                        + '"safe-json-stringify" module to have Bunyan fallback '
                        + 'to safer stringification. Record:\n'
                        + _indent(format('%s\n%s', util.inspect(rec), e.stack)),
                        dedupKey);
                    str = format('(Exception in JSON.stringify(rec): %j. '
                        + 'See stderr for details.)\n', e.message);
                }
            }
        }
    }

    if (noemit)
        return str;

    var level = rec.level;
    for (i = 0; i < this.streams.length; i++) {
        var s = this.streams[i];
        if (s.level <= level) {
            xxx('writing log rec "%s" to "%s" stream (%d <= %d): %j',
                rec.msg, s.type, s.level, level, rec);
            s.stream.write(s.raw ? rec : str);
        }
    };

    return str;
}
Esempio n. 3
0
          logsene.login(user, pass, function _loginAPICb(errApi, key) {
            spinner.stop();
            if (errApi) {
              out.error('Login was not successful' + stringify(errApi));
              return cb(
                new VError('Login was not successful. Possibly wrong username or password.', errApi)
              );
            }

            out.info('Successfuly logged in and retrieved API key.');
            cb(null, key);

          })
Esempio n. 4
0
  run: function _run() {

    if (argv.hasOwnProperty('trace')) {
      enableTrace(argv.trace);
    }

    // check explicitly for trace
    out.trace('Called with arguments: ' + stringify(argv));

    if (argv._.length < 2) {
      warnAndExit('Too few parameters!', this);
    } else if (argv._.length > 2) {
      warnAndExit('Too many parameters!', this);
    }

    if (isEmpty(argv['api-key'])
        && isEmpty(argv['token'])
        && isEmpty(argv['default-size'])
        && isEmpty(argv['range-separator'])
        && isEmpty(argv['trace'])) {
      warnAndExit('No known parameters specified.', this);
    }

    var setParam = function _setParam(paramName) {
      if (!isEmpty(argv[paramName])) {
        conf.setSync(camelCase(paramName), argv[paramName]);
        out.info('Successfuly set ' + paramName + ' to ' + argv[paramName]);
      }
    };

    // multiple option params allowed in a single command
    // slightly smelly is that I don't know
    // with which param the set command was called
    // so I have to check them all
    conf.getAvailableParams().forEach(function _forEachParam(param) {
      setParam(param);
    });


    process.exit(0); // bail out - that's it
  },
Esempio n. 5
0
var parseDuration = function _extractDuration(duration) {
  // maintenance: the following regex is explained in detail at the bottom of this file
  var r = /^\/?[+-]?P?([0-9]+[Yy])?([0-9]+M)?([0-9]+[Dd])?[Tt]?([0-9]+[Hh])?([0-9]+m|(?:[0-9]+m?(?![0-9]+[Ss])))?([0-9]+[Ss])?$/g;
  var matched = r.exec(duration);

  if (matched) {
    // clean up so that it contains only numbers as values
    var ret = {};
    if (matched[1]) ret.y = +matched[1].slice(0, -1);
    if (matched[2]) ret.M = +matched[2].slice(0, -1);
    if (matched[3]) ret.d = +matched[3].slice(0, -1);
    if (matched[4]) ret.h = +matched[4].slice(0, -1);
    if (matched[5]) ret.m = matched[5].indexOf('m') > -1 ? +matched[5].slice(0, -1) : +matched[5];
    if (matched[6]) ret.s = +matched[6].slice(0, -1);

    out.trace('parseDuration returned: ' + stringify(ret));
    return ret;

  } else {
    return false;
  }
};
Esempio n. 6
0
/**
 * A fast JSON.stringify that handles cycles and getter exceptions (when
 * safeJsonStringify is installed).
 *
 * This function attempts to use the regular JSON.stringify for speed, but on
 * error (e.g. JSON cycle detection exception) it falls back to safe stringify
 * handlers that can deal with cycles and/or getter exceptions.
 */
function fastAndSafeJsonStringify(rec) {
    try {
        return JSON.stringify(rec);
    } catch (ex) {
        try {
            return JSON.stringify(rec, safeCycles());
        } catch (e) {
            if (safeJsonStringify) {
                return safeJsonStringify(rec);
            } else {
                var dedupKey = e.stack.split(/\n/g, 3).join('\n');
                _warn('bunyan: ERROR: Exception in '
                    + '`JSON.stringify(rec)`. You can install the '
                    + '"safe-json-stringify" module to have Bunyan fallback '
                    + 'to safer stringification. Record:\n'
                    + _indent(format('%s\n%s', util.inspect(rec), e.stack)),
                    dedupKey);
                return format('(Exception in JSON.stringify(rec): %j. '
                    + 'See stderr for details.)', e.message);
            }
        }
    }
}
Esempio n. 7
0
    getApps(apiKey, function(err, logseneApps) {
      if (err) {
        out.error(err.message);
        out.error('Exiting');
        process.exit(1);
      }

      out.trace('API server returned these apps: ');
      out.trace(stringify(logseneApps));

      if (isNullOrUndefined(logseneApps)) {
        out.warn('There are no Logsene applications for your API key.\nExiting');
        process.exit(0);
      }


      // from now on, work only with active apps
      var activeApps = filter(logseneApps, function(app) {
        return app.appStatus.toUpperCase() === 'ACTIVE';
      });

      var activeAppsCnt = size(activeApps);
      out.trace('Total # of apps: ' + size(logseneApps));
      out.trace('# of active apps: ' + activeAppsCnt);


      // keep only a subset of useful keys per each app
      var apps = map(logseneApps, function(a) {
        return pick(a, ['app-key', 'name']);
      });

      out.trace('Picked only subset of app keys: ');
      out.trace(stringify(apps));


      if (activeAppsCnt === 0) {
        out.warn('There are no active Logsene apps for your apiKey.\nExiting...');
        process.exit(0);
      }

      out.trace('Active apps:\n');
      out.trace(stringify(activeApps));

      if (activeAppsCnt > 1) {
        // prompt user to choose one of active apps
        chooseApp(activeApps, function(err, chosenApp) {
          // error handled in chooseApp
          out.trace('Back in chooseApp callback.');

          conf.setSync('appKey', chosenApp.token);
          conf.setSync('appName', chosenApp.name);
          out.info('Successfuly established Logsene ' + chosenApp.name + ' application session.');
          return cb(null, true);
        });
      } else {
        // there's only one active Logsene app - use it without prompting the user
        conf.setSync('appKey', apps[0].token);
        conf.setSync('appName', apps[0].name);
        out.info('Successfuly established Logsene ' + apps[0].name + ' application session.');
        return cb(null, true);
      }
    });
Esempio n. 8
0
 }).map(function(arg) {
   return stringify(arg);
 });
Esempio n. 9
0
function logJson(data, level, stream, encoding) {
	var levelIndex = logLevels.indexOf(level);
	if(levelIndex !== -1 && levelIndex <= logLevels.indexOf(data.level)) {
		stream.write(safeJsonStringify(data) + '\n', encoding);
	}
}