Reputation: 93
I would like to programmatically get metrics relevant to the execution of Google cloud functions (e.g invocations, latency, etc.). Is there a (preferably simple) way to achieve this (e.g through an API)?
Upvotes: 1
Views: 2286
Reputation: 1035
Cloudfunctions is using Stackdriver to capture and display these metrics. (I assume you're looking for the same metrics that are displayed on each function in the console.) StackDriver has an API and client library where you can pull the metrics. More info on that at https://cloud.google.com/monitoring/docs/reference/libraries#client-libraries-install-nodejs .
Here's a small example of pulling these in node.js
const util = require("util");
// Imports the Google Cloud client library
const monitoring = require("@google-cloud/monitoring");
// Your Google Cloud Platform project ID
const projectId = "<YOUR PROJECT ID>";
// Creates a client
const client = new monitoring.MetricServiceClient({
keyFilename: "<YOUR CREDENTIALS>"
});
// list of metrics also avaliable at https://cloud.google.com/monitoring/api/metrics_gcp#gcp-cloudfunctions
// list all metrics avaliable
client
.listMetricDescriptors({
// name: `projects/${projectId}/monitoredResourceDescriptors/cloud_function`,
name: `projects/${projectId}`,
filter: 'metric.type = starts_with("cloudfunctions.googleapis.com")'
})
.then(results => {
console.log(results);
})
.catch(err => {
console.error("ERROR:", err);
});
const currentTime = new Date();
endTime = currentTime.toISOString();
startTime = new Date(currentTime - 1 * 60 * 60 * 1000).toISOString();
interval = {
startTime: {
// Limit results to the last 20 minutes
seconds: Date.now() / 1000 - 60 * 60
},
endTime: {
seconds: Date.now() / 1000
}
};
// get the executions accross time
client
.listTimeSeries({
name: `projects/${projectId}`,
filter:
'metric.type = "cloudfunctions.googleapis.com/function/execution_count" AND resource.label.function_name = "<YOUR FUNCTION NAME>"',
view: "FULL",
interval
})
.then(results => {
// console.log(results);
console.log(util.inspect(results, { showHidden: true, depth: 5 }));
})
.catch(err => {
console.error("ERROR:", err);
});
Upvotes: 3