Created
March 5, 2019 18:03
-
-
Save joshghent/d800ce464ec756c02ac6f9dc4441bed6 to your computer and use it in GitHub Desktop.
Graphite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Client } from "node-statsd-client"; | |
import { IGraphiteController } from "../interfaces"; | |
const PREFIX = "MY-API-NAME"; | |
export default class GraphiteController implements IGraphiteController { | |
private _client: any; | |
// the graphite port will always be this for every environment | |
private _port: number = 8125; | |
private static _instance: GraphiteController; | |
// Check if we are running tests, if so, deactive the graphite logging | |
private testing: boolean = process.env.NODE_ENV === "testing"; | |
constructor(config: any) { | |
if (!this.testing) { | |
try { | |
this._client = new Client(config.statsd, this._port); | |
} catch (err) { | |
throw new Error(`There was an error connecting to Graphite: ${err}`); | |
} | |
} | |
} | |
public static getInstance(config: any): GraphiteController { | |
if (!this._instance) { | |
this._instance = new GraphiteController(config); | |
} | |
return this._instance; | |
} | |
public write(activityType: string, error: boolean = false): void { | |
if (!this.testing) { | |
this._client.increment(`${PREFIX}.${activityType}${error ? ".error" : ""}`); | |
} | |
} | |
/** | |
* Writes a graphite timing | |
* This is used to measure the time a function or piece of logic takes | |
* @param {string} activityType | |
* @param {Date} startDate - a new Date() object. Create this as a variable at the top of the function and then pass it in | |
* @returns void | |
*/ | |
public writeTiming(activityType: string, startDate: Date): void { | |
if (!this.testing) { | |
this._client.timing(`${PREFIX}.${activityType}`, (new Date().getTime() - startDate.getTime())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment