import * as BatchedLogger from "./BatchedLogger"; const MetricTypeList = ["count", "gauge", "time"] as const; export type MetricType = typeof MetricTypeList[number]; export interface MetricsLog extends BatchedLogger.LogData { type: MetricType; } export class Metrics { /** * Count the number of times something has happened. * * Metrics.increment("page.load"); * Metrics.increment("page.load"); * Metrics.increment("apps.created", 4); * Metrics.increment("apps.created", 2); */ static increment(key: string, count = 1) { Metrics.log("count", key, count); } /** * Record the current value of something that changes over time. * * Metrics.gauge("cpu.load", 67); * Metrics.gauge("cpu.load", 32); */ static gauge(key: string, value: number) { Metrics.log("gauge", key, value); } /** * Time how long it takes to perform a task. * * Metrics.time("some.calculation", () => { calculateThings(); }); * Metrics.time("long.running", longRunningTask); */ static async time(key: string, fn: () => any) { const start = Date.now(); await fn(); this.timing(key, Date.now() - start); } /** * Record the time it took to perform a task. * * const duration = taskComplete - taskStart; * Metrics.timing("task.processing_time", duration); */ static timing(key: string, value: number) { Metrics.log("time", key, value); } static log(metricType: MetricType, key: string, value: number) { const item: MetricsLog = { type: metricType, key, value, }; BatchedLogger.addToBatch("metric", item); } }