Skip to content

Instantly share code, notes, and snippets.

@ottokruse
Last active March 3, 2021 08:37
Show Gist options
  • Save ottokruse/1c723bf7d4a28190a6531a759ffcf976 to your computer and use it in GitHub Desktop.
Save ottokruse/1c723bf7d4a28190a6531a759ffcf976 to your computer and use it in GitHub Desktop.
Simple AWS Lambda logger that uses CloudWatch Embedded Metric Format to create custom CloudWatch metrics (TypeScript)
// https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html
export function logCustomMetric(metric: {
dimensions: {
[key: string]: string;
};
namespace: string;
metrics: {
unit: Unit;
name: string;
value: number | number[];
}[];
}) {
if (metric.dimensions.length > 9) {
throw new Error("More than 9 dimensions provided");
}
if (metric.metrics.length > 100) {
throw new Error("More than 100 metric definitions provided");
}
const metricValues: { [key: string]: number | number[] } = {};
for (let metricDef of metric.metrics) {
if (metricValues[metricDef.name]) {
throw new Error(`Metric with name "${metricDef.name}" already provided`);
}
Object.assign(metricValues, { [metricDef.name]: metricDef.value });
}
console.log(
JSON.stringify(
{
...metric.dimensions,
...metricValues,
_aws: {
Timestamp: Date.now(),
CloudWatchMetrics: [
{
Dimensions: [Object.keys(metric.dimensions)],
Metrics: metric.metrics.map((metricDef) => ({
Name: metricDef.name,
Unit: metricDef.unit,
})),
Namespace: metric.namespace,
},
],
},
},
null,
2
)
);
}
export enum Unit {
Seconds = "Seconds",
Microseconds = "Microseconds",
Milliseconds = "Milliseconds",
Bytes = "Bytes",
Kilobytes = "Kilobytes",
Megabytes = "Megabytes",
Gigabytes = "Gigabytes",
Terabytes = "Terabytes",
Bits = "Bits",
Kilobits = "Kilobits",
Megabits = "Megabits",
Gigabits = "Gigabits",
Terabits = "Terabits",
Percent = "Percent",
Count = "Count",
BytesPerSecond = "Bytes/Second",
KilobytesPerSecond = "Kilobytes/Second",
MegabytesPerSecond = "Megabytes/Second",
GigabytesPerSecond = "Gigabytes/Second",
TerabytesPerSecond = "Terabytes/Second",
BitsPerSecond = "Bits/Second",
KilobitsPerSecond = "Kilobits/Second",
MegabitsPerSecond = "Megabits/Second",
GigabitsPerSecond = "Gigabits/Second",
TerabitsPerSecond = "Terabits/Second",
CountPerSecond = "Count/Second",
None = "None",
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment