Push stats data to InfluxDB.
492498
def _push_data(self):
        
        if not (self.config.series or self.config.series_host):
            self.LOG.info("Misconfigured InfluxDB job, neither 'series' nor 'series_host' is set!")
            return

        # Assemble data
        fluxdata = []

        if self.config.series:
            try:
                config_ini.engine.open()
                data, views = _flux_engine_data(config_ini.engine)
                fluxdata.append(dict(
                    name=self.config.series,
                    columns=data.keys(),
                    points=[data.values()]
                ))
                fluxdata.append(dict(
                    name=self.config.series + '_views',
                    columns=views.keys(),
                    points=[views.values()]
                ))
            except (error.LoggableError, xmlrpc.ERRORS), exc:
                self.LOG.warn("InfluxDB stats: {0}".format(exc))

#        if self.config.series_host:
#            fluxdata.append(dict(
#                name = self.config.series_host,
#                columns = .keys(),
#                points = [.values()]
#            ))

        if not fluxdata:
            self.LOG.debug("InfluxDB stats: no data (previous errors?)")
            return

        # Encode into InfluxDB data packet
        fluxurl = self._influxdb_url()
        fluxjson = json.dumps(fluxdata)
        self.LOG.debug("POST to {0} with {1}".format(fluxurl.split('?')[0], fluxjson))

        # Push it!
        try:
            # TODO: Use a session
            requests.post(fluxurl, data=fluxjson, timeout=self.influxdb.timeout)
        except RequestException, exc:
            self.LOG.info("InfluxDB POST error: {0}".format(exc))
938198
def put(self):
        """"""
        try:
            self.cloudwatch.put_metric_data(
                    Namespace=self.namespace,
                    MetricData=[{
                        'MetricName': self.name,
                        'Value': self.value,
                        'Timestamp': self.timestamp
                    }]
            )
        except Exception:
            logging.exception("Error pushing {0} to CloudWatch.".format(str(self)))
804890
def _send(self):
        
        # Check to see if we have a valid socket. If not, try to connect.
        try:
            if self.influx is None:
                self.log.debug("InfluxdbHandler: Socket is not connected. "
                               "Reconnecting.")
                self._connect()
            if self.influx is None:
                self.log.debug("InfluxdbHandler: Reconnect failed.")
            else:
                # build metrics data
                metrics = []
                for path in self.batch:
                    metrics.append({
                        "points": self.batch[path],
                        "name": path,
                        "columns": ["time", "value"]})
                # Send data to influxdb
                self.log.debug("InfluxdbHandler: writing %d series of data",
                               len(metrics))
                self.influx.write_points(metrics,
                                         time_precision=self.time_precision)

                # empty batch buffer
                self.batch = {}
                self.batch_count = 0
                self.time_multiplier = 1

        except Exception:
            self._close()
            if self.time_multiplier < 5:
                self.time_multiplier += 1
            self._throttle_error(
                "InfluxdbHandler: Error sending metrics, waiting for %ds.",
                2**self.time_multiplier)
            raise
570151
def add_namespace_statistics(self, namespace, offset, data_points,
                                 byte_count):
        """"""
        self.cursor.execute(
            'INSERT INTO gauged_statistics VALUES (%s,%s,%s,%s) ON DUPLICATE '
            'KEY UPDATE data_points = data_points + VALUES(data_points),'
            'byte_count = byte_count + VALUES(byte_count)',
            (namespace, offset, data_points, byte_count))
349541
def export(self, name, columns, points):
        """"""
        logger.debug("Export {} stats to CouchDB".format(name))

        # Create DB input
        data = dict(zip(columns, points))

        # Set the type to the current stat name
        data['type'] = name
        data['time'] = couchdb.mapping.DateTimeField()._to_json(datetime.now())

        # Write input to the CouchDB database
        # Result can be view: http://127.0.0.1:5984/_utils
        try:
            self.client[self.db].save(data)
        except Exception as e:
            logger.error("Cannot export {} stats to CouchDB ({})".format(name, e))
808856
def export(self, name, columns, points):
        """"""
        logger.debug("Export {} stats to Prometheus exporter".format(name))

        # Remove non number stats and convert all to float (for Boolean)
        data = {k: float(v) for (k, v) in iteritems(dict(zip(columns, points))) if isinstance(v, Number)}

        # Write metrics to the Prometheus exporter
        for k, v in iteritems(data):
            # Prometheus metric name: prefix_<glances stats name>
            metric_name = self.prefix + self.METRIC_SEPARATOR + str(name) + self.METRIC_SEPARATOR + str(k)
            # Prometheus is very sensible to the metric name
            # See: https://prometheus.io/docs/practices/naming/
            for c in ['.', '-', '/', ' ']:
                metric_name = metric_name.replace(c, self.METRIC_SEPARATOR)
            # Get the labels
            labels = self.parse_tags(self.labels)
            # Manage an internal dict between metric name and Gauge
            if metric_name not in self._metric_dict:
                self._metric_dict[metric_name] = Gauge(metric_name, k,
                                                       labelnames=listkeys(labels))
            # Write the value
            if hasattr(self._metric_dict[metric_name], 'labels'):
                # Add the labels (see issue #1255)
                self._metric_dict[metric_name].labels(**labels).set(v)
            else:
                self._metric_dict[metric_name].set(v)
1040776
def store_stats(self):
    """"""
    stats = self._stats()

    # Write stats to user-defined json file.
    stats_json_file_name = self.get_options().stats_local_json_file
    if stats_json_file_name:
      self.write_stats_to_json(stats_json_file_name, stats)

    # Upload to remote stats db.
    stats_upload_urls = copy.copy(self.get_options().stats_upload_urls)
    timeout = self.get_options().stats_upload_timeout
    for stats_url, auth_provider in stats_upload_urls.items():
      self.post_stats(stats_url, stats, timeout=timeout, auth_provider=auth_provider)
302078
def gauge(self, stats, value):
        
        self.update_stats(stats, value, self.SC_GAUGE)
450204
function logStat(stat, value) {
  if (!statsTracker[stat]) {
    statsTracker[stat] = [];
  }
  statsTracker[stat].push(value);
  clearTimeout(statsTimer);
  statsTimer = setTimeout(printStats, 100);
}
16060
def register_stats_handler(app, server_name, prefix='/status/'):
    """"""
    if not prefix.endswith('/'):
        prefix += '/'
    handler = functools.partial(bottlestats, server_name)

    app.get(prefix, callback=handler)
    app.get(prefix + '<path:path>', callback=handler)
217253
def export(self, name, columns, points):
        """"""
        for i in range(len(columns)):
            if not isinstance(points[i], Number):
                continue
            stat_name = '{}.{}.{}'.format(self.prefix, name, columns[i])
            stat_value = points[i]
            tags = self.parse_tags(self.tags)
            try:
                self.client.send(stat_name, stat_value, **tags)
            except Exception as e:
                logger.error("Can not export stats %s to OpenTSDB (%s)" % (name, e))
        logger.debug("Export {} stats to OpenTSDB".format(name))
173461
def export(self, name, columns, points):
        """"""
        for i in range(len(columns)):
            if not isinstance(points[i], Number):
                continue
            else:
                data = {'host': self.hostname, 'service': name + " " + columns[i], 'metric': points[i]}
                logger.debug(data)
                try:
                    self.client.send(data)
                except Exception as e:
                    logger.error("Cannot export stats to Riemann (%s)" % e)
467406
def stats(request, date_offset=0, fields=None, title_prefix=None, model='WikiItem'):
    
    data = {}

    modified_chart_data = data['chart']['chartdata']
    if 'y2' in data['chart']['chartdata']:
        matrix = db.Columns([modified_chart_data['y1'], modified_chart_data['y2']], ddof=0, tall=True)
    else:
        fields = ['date/time'] + fields
        matrix = db.Columns([modified_chart_data['x'], modified_chart_data['y']], ddof=0, tall=True)
    if fields and len(fields) > 1:
        fields = fields[:2]
    else:
        fields = [
            data['chart']['chartdata'].get('name1') or 'time',
            data['chart']['chartdata'].get('name2') or data['chart']['chartdata'].get('name') or 'value',
            ]
    fields = util.pluralize_field_names(fields)
    data.update({
        'stats': {
            'fields': fields,
            'heading': 'Statistics',
            'cov': zip(fields, matrix.cov()),
            'R': zip(fields, matrix.rho),
            },
        })
    data['chart']['chartdata'] = modified_chart_data
    data['chart']['chart_title'] = 'Time Series'
    return render_to_response('miner/stats.html', data)
625328
def push(self, statsDict=None, prefix=None, path=None):
    """"""
    if statsDict is None:
      statsDict = scales.getStats()
    prefix = prefix or self.prefix
    path = path or '/'

    for name, value in list(statsDict.items()):
      name = str(name)
      subpath = os.path.join(path, name)

      if self._pruned(subpath):
        continue

      if hasattr(value, '__call__'):
        try:
          value = value()
        except:                       # pylint: disable=W0702
          value = None
          log.exception('Error when calling stat function for graphite push')

      if hasattr(value, 'items'):
        self.push(value, '%s%s.' % (prefix, self._sanitize(name)), subpath)
      elif self._forbidden(subpath, value):
        continue

      if six.PY3:
        type_values = (int, float)
      else:
        type_values = (int, long, float)

      if type(value) in type_values and len(name) < 500:
        self.graphite.log(prefix + self._sanitize(name), value)
925750
def spread_stats    
      @items = basic_collection.between_dates(@stat_from, @stat_thru)
      
      handle_special_fields
       
      data = {
        alternatives: [
          {
            type: 'spread'
          },
          {
            type: 'process',
            uri: url_for(action: "process_stats", field: params[:field], filters: params[:filters], only_path: true)
          }
        ],   
        from: @stat_from.to_time.utc.to_i * 1000,
        thru: @stat_thru.to_time.utc.to_i * 1000,
        total: @items.count(:id),
        data: @items.count_by(params[:field])
      }
      
      if further_details.keys.include? params[:field]
        filters = (params[:filters] || {})
        filters[params[:field]] = '%{self}'
        
        data[:detail_uri] = url_for(action: "spread_stats", field: further_details[params[:field]], filters: filters, only_path: true)
      end
      
      render json: data
    end
137801
def update(self):
        """"""
        # Init new stats
        stats = self.get_init_value()

        if self.input_method == 'local':
            for k, v in iteritems(self.glances_amps.update()):
                stats.append({'key': k,
                              'name': v.NAME,
                              'result': v.result(),
                              'refresh': v.refresh(),
                              'timer': v.time_until_refresh(),
                              'count': v.count(),
                              'countmin': v.count_min(),
                              'countmax': v.count_max()})
        else:
            # Not available in SNMP mode
            pass

        # Update the stats
        self.stats = stats

        return self.stats
538181
def maybe_submit_measurement(self):
        
        if self.statsd:
            self.submit_statsd_measurements()
        if self.influxdb:
            self.submit_influxdb_measurement()