From 52bb28669a62da31659b90bfd287f0bf06f629fd Mon Sep 17 00:00:00 2001 From: mikiher Date: Sat, 8 Feb 2025 10:41:56 +0200 Subject: [PATCH] Add a profile utility function --- server/utils/profiler.js | 41 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 server/utils/profiler.js diff --git a/server/utils/profiler.js b/server/utils/profiler.js new file mode 100644 index 00000000..614ce5b7 --- /dev/null +++ b/server/utils/profiler.js @@ -0,0 +1,41 @@ +const { performance, createHistogram } = require('perf_hooks') +const util = require('util') +const Logger = require('../Logger') + +const histograms = new Map() + +function profile(asyncFunc, isFindQuery = true, funcName = asyncFunc.name) { + if (!histograms.has(funcName)) { + const histogram = createHistogram() + histogram.values = [] + histograms.set(funcName, histogram) + } + const histogram = histograms.get(funcName) + + return async (...args) => { + if (isFindQuery) { + const findOptions = args[0] + Logger.info(`[${funcName}] findOptions:`, util.inspect(findOptions, { depth: null })) + findOptions.logging = (query, time) => Logger.info(`[${funcName}] ${query} Elapsed time: ${time}ms`) + findOptions.benchmark = true + } + const start = performance.now() + try { + const result = await asyncFunc(...args) + return result + } catch (error) { + Logger.error(`[${funcName}] failed`) + throw error + } finally { + const end = performance.now() + const duration = Math.round(end - start) + histogram.record(duration) + histogram.values.push(duration) + Logger.info(`[${funcName}] duration: ${duration}ms`) + Logger.info(`[${funcName}] histogram values:`, histogram.values) + Logger.info(`[${funcName}] histogram:`, histogram) + } + } +} + +module.exports = { profile }