Skip to content

Changes yash #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "airbnb-base",
"rules": {
"no-await-in-loop": 0,
"one-var": 0,
"max-len": ["error", { "code": 250 }],
"import/no-extraneous-dependencies": 1,
"no-underscore-dangle": [2, { "allow": ["_id"]} ],
"indent": ["error", 2]
}
}
43 changes: 31 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,35 @@ All you need to be aware of are the methods of this SDK and all the methods retu
# Sample Usage -

```
var mongoUtils = require('mongodb-nodejs-sdk');

var doSomethingWithTheSetOfDocuments = function doSomethingWithTheSetOfDocuments(){
return mongoUtils.findDocumentsBasedOnQuery('mongoCollectionName', {status: "done"}, 0, {_id: 0})
.then(function(documents){
console.log(`Documents found in collection mongoCollectionName`, documents.length);
return Promise.resolve(documents); //Do anything with the set of returned documents.
})
.catch(function(error){
return Promise.reject(error);
});
};

const mongoUtils = require('./utils');

mongoUtils.initialize(DB_URL).then(async (resp) => {
console.log('connected', resp);
const resp = await mongoUtils.insertIntoDb('testCollection', ['asds','dasdsa','dasds']);
});

```


const PromClient = require('./prometheus');


await PromClient.initialize({ job: 'jobName', instance: myIP() });
PromClient.expressMiddleware(app);
PromClient.serveExpressMetrics(app);


const counter = PromClient.getCounter({ name: 'nodejs_product_service', help: 'metric_help', labelNames: ['status', 'state'] });
counter.inc({ status: 'retry', state: '0' });
counter.inc({ status: 'fail', state: '0' });


const histogram = PromClient.getHistogram({
name: 'nodejs_http_request_duration_seconds',
help: 'metric_help',
labelNames: ['route'],
buckets,
});
const end = histogram.startTimer();
end({ route, method });
8 changes: 7 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@
"bluebird": "3.5.0",
"documentation": "6.3.0",
"lodash": "4.17.4",
"mongodb": "2.2.29"
"mongodb": "2.2.29",
"prom-client": "11.2.1"
},
"devDependencies": {
"eslint": "^3.14.1",
"eslint-config-airbnb": "^14.0.0",
"eslint-plugin-import": "^2.2.0"
}
}
106 changes: 106 additions & 0 deletions prometheus.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
const client = require('prom-client');
const _ = require('lodash');


class PromClient {

/**
* Method to initialize prometheus
* @param {string} defaultLabels Dictionary with key representing label name and value the label value. This will be appended to all the metrics
* @returns {object} Prometheus client object (does not need to be used though)
*/
static initialize(defaultLabels) {
// This needs to be initialized only after Log
//check if log library is initialised
// console.log()
if (PromClient.client) return PromClient.client;
const registry = new client.Registry();
registry.setDefaultLabels(defaultLabels);

client.collectDefaultMetrics({ register: registry });
PromClient.client = registry;

PromClient.collectPromiseRejections();
return PromClient.client;
}

/**
* Method to create event listeners to record promise rejections for the whole service
*/
static collectPromiseRejections() {
process.on('unhandledRejection', (reason) => {
const counter = PromClient.getCounter({ name: 'nodejs_promise_unhandled_rejection_count', help: 'metric_help' });
counter.inc();
});

process.on('rejectionHandled', () => {
const counter = PromClient.getCounter({ name: 'nodejs_promise_handled_rejection_count', help: 'metric_help' });
counter.inc();
});
}

/**
* Method to serve metrics collected
* @param {object} app app object
* @param {string} url if you want the exposed url to be something other than default metrics
* @returns {null}
*/
static serveExpressMetrics(app, url) {
if (!PromClient.client) throw new Error('PromClient not initialized');
if (_.isNil(url)) app.get('/metrics', (req, res) => res.end(PromClient.client.metrics()));
else app.get(url, (req, res) => res.end(PromClient.client.metrics()));
}

/**
* Method to create histograms to record time taken to serve all URL's
* @param {object} app app object
* @param {array} bkts time buckets to be created for the histogram
* @returns {null}
*/
static expressMiddleware(app, bkts) {
// Register this before paths
if (!PromClient.client) throw new Error('PromClient not initialized');
const buckets = !_.isNil(bkts) ? bkts : [0.01, 0.1, 0.2, 0.3, 0.4, 0.5, 1, 5, 10, 60, 120];
app.use((req, res, next) => {
const histogram = PromClient.getHistogram({
name: 'nodejs_http_request_duration_seconds',
help: 'metric_help',
labelNames: ['route'],
buckets,
});
const end = histogram.startTimer();
const route = req.path;
const { method } = req;
res.on('header', () => {
end({ route, method });
});
next();
});
}

static getCounter(config) {
if (!config || !config.name) throw new Error('Invalid arguments');
if (!PromClient.client) throw new Error('PromClient not initialized');
let counter = PromClient.client.getSingleMetric(config.name);
if (!counter) {
const newConfig = _.cloneDeep(config);
newConfig.registers = [PromClient.client];
counter = new client.Counter(newConfig);
}
return counter;
}

static getHistogram(config) {
if (!config || !config.name) throw new Error('Invalid arguments');
if (!PromClient.client) throw new Error('PromClient not initialized');
let histogram = PromClient.client.getSingleMetric(config.name);
if (!histogram) {
const newConfig = _.cloneDeep(config);
newConfig.registers = [PromClient.client];
histogram = new client.Histogram(newConfig);
}
return histogram;
}
}

module.exports = PromClient;
Loading