Skip to content

Commit

Permalink
Merge pull request #9 from Serphentas/fix-timestamp
Browse files Browse the repository at this point in the history
Fix #6
  • Loading branch information
Serphentas authored Jan 15, 2018
2 parents a349370 + b93d73b commit 675ba85
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
19 changes: 15 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,35 @@ npm install graphite

## Usage

Sending data:
You first have to define the Graphite client:

```js
var graphite = require('graphite');
var client = graphite.createClient('plaintext://graphite.example.org:2003/');
```

You can send metrics without a timestamp. The current Unix epoch will then be used in place:

```js
var metrics = {foo: 23};
client.write(metrics, function(err) {
// if err is null, your data was sent to graphite!
});
```

Sending data with tags:
If you wish to set your own timestamp, you must use `Date.now()` (millisecond precision) as parameter and not `Math.floor(Date.now() / 1000)` (second precision), otherwise your metrics will probably get ignored by Graphite:

```js
var graphite = require('graphite');
var client = graphite.createClient('plaintext://graphite.example.org:2003/');
var metrics = {foo: 23};
var timestamp = Date.now();
client.write(metrics, timestamp, function(err) {
// if err is null, your data was sent to graphite!
});
```

In Graphite [1.1.1 (21.12.17)](http://graphite.readthedocs.io/en/latest/releases/1_1_1.html), [tagging](http://graphite.readthedocs.io/en/latest/tags.html) becomes available. You can send tagged metrics as follows:

```js
var metrics = {foo: 23};
var tags = {'name': 'foo.bar', 'some.fancy.tag': 'somefancyvalue'};
client.writeTagged(metrics, tags, function(err) {
Expand Down
18 changes: 15 additions & 3 deletions lib/GraphiteClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,25 @@ GraphiteClient.appendTags = function(flatMetrics, tags) {
return res;
};

/**
* Writes the given metrics to the underlying plaintext socket to Graphite
*
* If no timestamp is given, the current Unix epoch is used (second precision).
*
* If a timestamp is provided, it must have a millisecond precision, otherwise
* Graphite will probably reject the data.
*
* @param {object} metrics
* @param {object} timestamp
* @param {function} cb
*/
GraphiteClient.prototype.write = function(metrics, timestamp, cb) {
if (typeof timestamp === 'function') {
cb = timestamp;
timestamp = null;
cb = timestamp;
timestamp = Date.now();
}

timestamp = timestamp || Date.now();
// cutting timestamp for precision up to the second
timestamp = Math.floor(timestamp / 1000);

this._carbon.write(GraphiteClient.flatten(metrics), timestamp, cb);
Expand Down

0 comments on commit 675ba85

Please sign in to comment.