Skip to content

Commit

Permalink
Merge pull request #30 from ysa23/chore/standardization
Browse files Browse the repository at this point in the history
Chore: standardization
  • Loading branch information
ysa23 committed Feb 8, 2022
2 parents b9fac5b + 04c5179 commit ceb0eae
Show file tree
Hide file tree
Showing 24 changed files with 448 additions and 313 deletions.
62 changes: 36 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@ Metrics is a time series reporting framework for to aggregators and metrics coll
![Lint and tests](https://github.com/ysa23/metrics-js/workflows/Lint%20and%20tests/badge.svg)
![Node.js Publish to NPM](https://github.com/ysa23/metrics-js/workflows/Node.js%20Publish%20to%20NPM/badge.svg)


## Highlights
* Time series reporting
* Plugin based: Support different aggregators with plugable reporters
* Plugin based: Support different aggregators with pluggable reporters
* Built in [reporters](#Reporters):
* [Graphite (statsd)](#Graphite)
* [DataDog](#DataDog)
Expand Down Expand Up @@ -51,12 +50,12 @@ Initialize the metrics instance with the required reporters:
```js
const { StringReporter, ConsoleReporter } = require('metrics-reporter');

const stringReporter = new StringReporter(metricString => {
const stringReporter = new StringReporter({ action: metricString => {
// Do something
});
}});
const consoleReporter = new ConsoleReporter();

const metrics = new Metrics([stringReporter, consoleReporter], errorCallback);
const metrics = new Metrics({ reporters: [stringReporter, consoleReporter], errback: errorCallback });
```

### Reporting Metrics
Expand Down Expand Up @@ -110,7 +109,7 @@ const result = await metrics.space('users.get').meter(async () => {
// Some async code here
})();
```
Please note the invocation on the return value.
**Please note the invocation on the return value.**

#### Value
Use the `Metrics` instance to report a value:
Expand Down Expand Up @@ -143,9 +142,12 @@ When the same tag is specified when creating nested spaces, the last value will
#### Error handling
Metrics support error handling. When creating a Metric object you can send an error callback:
```js
const metrics = new Metrics([new ConsoleReporter()], e => {
const metrics = new Metrics({
reporters: [new ConsoleReporter()],
errback: e => {
// e is a javascript Error object. You can log it on any standard logging framework:
logger.error(e);
}
});
```
The error callback receives a single parameter - an Error instance. The callback will be triggered when any error occurs during the metrics reporting
Expand Down Expand Up @@ -175,7 +177,7 @@ const graphiteReporter = new GraphiteReporter({
flushInterval,
});

const metrics = new Metrics([graphiteReporter], errorCallback);
const metrics = new Metrics({ reporters: [graphiteReporter] });

graphiteReporter.close(); // close should be called when the application terminates
```
Expand All @@ -191,7 +193,7 @@ const spacePrefix = 'My.Project'; // Optional - prefix to all metrics spac
const batch = true; // Optional - Default `true` - Indicates that metrics will be sent in batches
const maxBufferSize = 500; // Optional - Default `1000` - Size of the buffer for sending batched messages. When buffer is filled it is flushed immediately
const flushInterval = 1000; // Optional - Default `1000` (1s) - Time in milliseconds. Indicates how often the buffer is flushed in case batch = true
const defaultTags = { tag1: 'value1' }; // Optional - key-value pairs to be appanded to all the metrics reported
const tags = { tag1: 'value1' }; // Optional - key-value pairs to be appanded to all the metrics reported

const datadogReporter = new DataDogReporter({
host: agentHost,
Expand All @@ -200,10 +202,10 @@ const datadogReporter = new DataDogReporter({
batch,
maxBufferSize,
flushInterval,
defaultTags,
tags,
});

const metrics = new Metrics([datadogReporter], errorCallback);
const metrics = new Metrics({ reporters: [datadogReporter] });

datadogReporter.close(); // close should be called when the application terminates
```
Expand All @@ -212,24 +214,26 @@ Note that you'll need a running [DataDog agent](https://docs.datadoghq.com/agent
#### Console
Console reporter comes in handy when you need to debug metrics calls:
```js
const { Metrics } = require('metrics-reporter');
const { Metrics, ConsoleReporter } = require('metrics-reporter');

const consoleReporter = new require('metrics-reporter').ConsoleReporter();
const consoleReporter = new ConsoleReporter();

const metrics = new Metrics([consoleReporter], errorHandler);
const metrics = new Metrics({ reporters: [consoleReporter] });
```
When a metrics will be reported, a message will appear in the terminal, that includes the key and the value reported.

#### String
```js
const { Metrics } = require('metrics-reporter');
const { Metrics, StringReporter } = require('metrics-reporter');
const fs = require('fs');

const stringReporter = new require('metrics-reporter').StringReporter(metricString => {
fs.appendFile('metrics.log', metricsString);
const stringReporter = new StringReporter({
action: metricString => {
fs.appendFile('metrics.log', metricsString);
},
});

const metrics = new Metrics([stringReporter], errorHandler);
const metrics = new Metrics({ reporters: [stringReporter] });
```
Here, `StringReporter` is used to build a log file from the metrics reports.

Expand All @@ -240,9 +244,9 @@ const { Metrics, InMemoryReporter } = require('metrics-reporter');

const metricsStorage = [];

const memoryReporter = new InMemoryReporter(metricsStorage);
const metrics = new Metrics([memoryReporter], error => { /* Do something on error */ });
const memoryReporter = new InMemoryReporter({ buffer: metricsStorage });

const metrics = new Metrics({ reporters: [memoryReporter], errback: error => { /* Do something on error */ } });
```
When a metric is reported, an object with `key`, `value` and `tags` properties is pushed to the array.<br/>
Then, the array can be used in order to validate the report.
Expand All @@ -266,22 +270,28 @@ For example, lets see how to implement a reporter for redis:
const client = require('redis').createClient();

module.exports = function RedisReporter(channel) {
this.report = function(key, value, tags, errorCallback) {
client.publish(channel, JSON.stringify({ key, value, tags }));
function report(key, val, tags, errorCallback) {
client.publish(channel, JSON.stringify({ key, value: val, tags }));
}

this.value = function(key, value, tags, errorCallback) {
client.set(key, value, errorCallback);
function value(key, val, tags, errorCallback) {
client.set(key, val, errorCallback);
}

this.increment = function(key, value, tags, errorCallback) {
function increment(key, value, tags, errorCallback) {
const multi = client.multi();
for(let i = 0; i < value; i++) {
multi.incr(key);
}

multi.exec(errorCallback);
}

return {
report,
value,
increment,
}
};
```
The new reporter will publish a message to a specified channel in redis when a metric is reported.
Expand Down
6 changes: 0 additions & 6 deletions index.js

This file was deleted.

9 changes: 0 additions & 9 deletions metrics.js

This file was deleted.

83 changes: 0 additions & 83 deletions metrics.test.js

This file was deleted.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"name": "metrics-reporter",
"description": "Metrics reporting framework for reporting data point information to aggregators (like Graphite)",
"main": "./src/index.js",
"license": "MIT",
"keywords": [
"metrics",
Expand All @@ -9,14 +10,14 @@
"datadog",
"DogStatsD"
],
"version": "0.10.1",
"version": "0.11.0",
"repository": {
"type": "git",
"url": "https://github.com/ysa23/metrics-js"
},
"scripts": {
"test": "jest --runInBand --forceExit --detectOpenHandles",
"lint": "eslint index.js .",
"lint": "eslint src/index.js .",
"example:graphite": "node ./examples/graphite.js",
"example:datadog": "node ./examples/datadog.js",
"docker:datadog:up": "cd ./docker && docker-compose -f docker-compose-datadog.yml up -d",
Expand Down
20 changes: 0 additions & 20 deletions reporters/in-memory-reporter.js

This file was deleted.

36 changes: 0 additions & 36 deletions reporters/string-reporter.js

This file was deleted.

15 changes: 15 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const { ConsoleReporter } = require('./reporters/console-reporter');
const { DataDogReporter } = require('./reporters/datadog-reporter');
const { GraphiteReporter } = require('./reporters/graphite-reporter');
const { InMemoryReporter } = require('./reporters/in-memory-reporter');
const { StringReporter } = require('./reporters/string-reporter');
const { Metrics } = require('./metrics');

module.exports = {
Metrics,
ConsoleReporter,
DataDogReporter,
GraphiteReporter,
InMemoryReporter,
StringReporter,
};
24 changes: 24 additions & 0 deletions src/metrics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const { Space } = require('./space');

function Metrics({ reporters, errback }) {
if (!reporters || !Array.isArray(reporters) || reporters.length === 0) throw new TypeError('reporters is missing or empty');
if (errback && typeof errback !== 'function') throw new TypeError('errback must be a function');

if (!reporters.every(r => r && typeof r.report === 'function' && typeof r.value === 'function' && typeof r.increment === 'function')) {
throw new TypeError('must pass valid reporters with a `report` function');
}

function space(key, tags) {
return new Space({
key, tags, reporters, errback,
});
}

return {
space,
};
}

module.exports = {
Metrics,
};
Loading

0 comments on commit ceb0eae

Please sign in to comment.