来自浏览器JS / AJAX的Prometheus Pushgateway

时间:2019-03-07 08:07:50

标签: javascript client prometheus

我正在寻找有关如何通过ajax将度量标准推送到Pushgateway的示例。

echo 'some_metric 42' | curl --user user:pass --data-binary @- https://example.com/metrics/job/author_monitoring/jobname/count_open

卷曲,效果很好!

我不知道如何在js / jquery中进行翻译。 也许有人举个例子

这是我到目前为止所得到的。

(function ($, $document) {
  "use strict";

  function textToBin(text) {
    return (
      Array
      .from(text)
      .reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
      .map(bin => '0'.repeat(8 - bin.length) + bin)
      .join(' ')
    );
  }

  var username = "user";
  var password = "pass";
  var metric = 'some_metric 42';
  var binaryData = textToBin(metric);

  $.ajax({
    url: "https://example.com/metrics/job/author_monitoring/jobname/count_open",
    data: binaryData,
    type: 'POST',
    crossDomain: true,
    beforeSend: function (xhr) {
      xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
    },
    success: function () {
      console.log("Success");
    },
    error: function () {
      console.log('Failed!');
    }
  });

})($, $(document));

这是错误:

text format parsing error in line 1: invalid metric name

1 个答案:

答案 0 :(得分:0)

好吧,我明白了。

有一个简单的解决方案,导入是在字符串末尾的\n

(function ($, $document) {
  "use strict";
  var username = "user";
  var password = "pass";
  var metric = 'some_metric 42\n';

  $.ajax({
    url: "https://example.com/metrics/job/author_monitoring/jobname/count_open",
    data: metric,
    type: 'POST',
    beforeSend: function (xhr) {
      xhr.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
      xhr.setRequestHeader("Content-Type", "text/plain");
    },
    success: function () {
      console.log("Success");
    },
    error: function () {
      console.log('Failed!');
    }
  });
})($, $(document));