Skip to content

Commit

Permalink
Support JSON logging
Browse files Browse the repository at this point in the history
  • Loading branch information
alexcasalboni committed Feb 9, 2024
1 parent 5ecb337 commit daa93a7
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions lambda/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -520,13 +520,42 @@ module.exports.computeAverageDuration = (durations, discardTopBottom) => {
* Extract duration (in ms) from a given Lambda's CloudWatch log.
*/
module.exports.extractDuration = (log) => {
if (log.charAt(0) === '{') {
// extract from JSON (multi-line)
return utils.extractDurationFromJSON(log);
} else {
// extract from text
return utils.extractDurationFromText(log);
}
};

/**
* Extract duration (in ms) from a given text log.
*/
module.exports.extractDurationFromText = (log) => {
const regex = /\tBilled Duration: (\d+) ms/m;
const match = regex.exec(log);

if (match == null) return 0;
return parseInt(match[1], 10);
};

/**
* Extract duration (in ms) from a given JSON log (multi-line).
*/
module.exports.extractDurationFromJSON = (log) => {
// extract each line and parse it to JSON object
const lines = log.split('\n').map((line) => JSON.parse(line))

// find the log corresponding to the invocation report
const durationLine = lines.find((line) => line.type === 'platform.report');
if (durationLine){
return durationLine.record.metrics.billedDurationMs;
}

throw new Error("Unrecognized JSON log");
};

/**
* Encode a given string to base64.
*/
Expand Down

0 comments on commit daa93a7

Please sign in to comment.