import { StatsCb , StatsD , Tags } from "hot-shots" ; import { getLogger } from "./logger" ; import { NextFunction , Request , Response } from "express" ; import { isNodeDev , isNodeTest } from "../util/isNodeEnv" ; import { metricHttpRequest } from "./metric-names" ; export const globalTags = { environment : isNodeTest ( ) ? "test" : process . env . MICROS_ENV || "" , environment_type : isNodeTest ( ) ? "testenv" : process . env . MICROS_ENVTYPE || "" , deployment_id : process . env . MICROS_DEPLOYMENT_ID || "1" , region : process . env . MICROS_AWS_REGION || "us-west-1" } ; const RESPONSE_TIME_HISTOGRAM_BUCKETS = "100_1000_2000_3000_5000_10000_30000_60000" ; const logger = getLogger ( "config.statsd" ) ; const statsd = new StatsD ( { prefix : "github-for-jira." , host : "platform-statsd" , port : 8125 , globalTags , errorHandler : ( err ) => { if ( ! isNodeDev ( ) ) { logger . warn ( err , "Error writing metrics" ) ; } } , mock : isNodeTest ( ) } ) ; returns { function ( ) : number } function hrtimer ( ) { const start = process . hrtime ( ) ; return ( ) => { const durationComponents = process . hrtime ( start ) ; const seconds = durationComponents [ 0 ] ; const nanoseconds = durationComponents [ 1 ] ; return seconds * 1000 + nanoseconds / 1e6 ; } ; } param path export const elapsedTimeMetrics = ( req , res , next ) => { const elapsedTimeInMs = hrtimer ( ) ; const method = req . method ; ( req . log || logger ) . debug ( { method : req . method , path : req . path , body : JSON . stringify ( req . body ) , query : req . query } , `${ method } request initialized for path ${ req . path }` ) ; res . once ( "finish" , ( ) => { const elapsedTime = elapsedTimeInMs ( ) ; const statusCode = `${ res . statusCode }` ; const path = ( req . baseUrl || "" ) + ( req . route ?. path || "/*" ) ; const tags = { path , method , statusCode } ; ( req . log || logger ) . debug ( `${ method } request executed in ${ elapsedTime } with status ${ statusCode } path ${ path }` ) ; statsd . histogram ( metricHttpRequest . duration , elapsedTime , tags ) ; statsd . histogram ( metricHttpRequest . duration , elapsedTime , { ... tags , gsd_histogram : RESPONSE_TIME_HISTOGRAM_BUCKETS } ) ; statsd . increment ( metricHttpRequest . executed , tags ) ; } ) ; next ( ) ; } ; /**
 * Async Function Timer using Distributions
 */ export function asyncDistTimer ( func , stat , sampleRate ? , tags ? , callback ? ) { return ( ... args ) : Promise < unknown > => { const end = hrtimer ( ) ; const p = func ( ... args ) ; const recordStat = ( ) => statsd . distribution ( stat , end ( ) , sampleRate , tags , callback ) ; p . then ( recordStat , recordStat ) ; return p ; } ; } export default statsd ;