Created
July 11, 2024 08:26
-
-
Save 0xdeepmehta/8cf6ef1d5e4039b4d5592497b406a76b to your computer and use it in GitHub Desktop.
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
async function profiledFunctionExecution(asyncFunctionToProfile, functionName, additionalData = []) { | |
const startTime = Date.now(); | |
const PROFILE_LOG_PREFIX = "[PROFILING]"; | |
// Start a transaction for monitoring (assuming a monitoring library is used) | |
const transaction = startTransaction({ name: functionName }); | |
// Log the start of function execution | |
console.log(PROFILE_LOG_PREFIX, `function=${functionName} event=start ts=${new Date(startTime).toISOString()}`); | |
// Add any additional data to the transaction | |
additionalData.forEach(([key, value]) => { | |
transaction.setData(key, value); | |
}); | |
let result; | |
try { | |
// Execute the function we're profiling | |
result = await asyncFunctionToProfile; | |
} catch (error) { | |
// If an error occurs, mark the transaction as errored and re-throw | |
transaction.setStatus("error"); | |
throw error; | |
} | |
const endTime = Date.now(); | |
const durationInSeconds = (endTime - startTime) / 1000; | |
// Log the end of function execution | |
console.log(PROFILE_LOG_PREFIX, `function=${functionName} event=finish ts=${new Date(endTime).toISOString()}`); | |
console.log(PROFILE_LOG_PREFIX, `function=${functionName} event=measure duration=${durationInSeconds.toFixed(2)} seconds`); | |
// Set the duration measurement in the transaction if the method exists | |
if (transaction && typeof transaction.setMeasurement === "function") { | |
transaction.setMeasurement("duration", durationInSeconds, "second"); | |
} | |
// Finish the transaction | |
transaction.finish(); | |
// Return the result of the profiled function | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment