### Install Go Client Library Source: https://docs.cloud.google.com/monitoring/docs/reference/libraries Install the Go client library for Cloud Monitoring using the go get command. ```go go get cloud.google.com/go/monitoring/apiv3 ``` -------------------------------- ### Install PHP Client Library Source: https://docs.cloud.google.com/monitoring/docs/reference/libraries Install the PHP client library for Cloud Monitoring using composer. ```php composer require google/cloud-monitoring ``` -------------------------------- ### Create Uptime Check Configuration (GET Request) in Python Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-uptime-check-create Creates a new uptime check configuration using a GET request with the Python client library. This example specifies the project ID, host name, and display name. Authentication is handled via Application Default Credentials. ```python def create_uptime_check_config_get( project_id: str, host_name: str = None, display_name: str = None ) -> uptime.UptimeCheckConfig: """Creates a new uptime check configuration Args: project_id: Google Cloud project id where the uptime check is created host_name: An example label's value for the "host" label display_name: A human friendly name of the configuration Returns: A structure that describes a new created uptime check """ config = monitoring_v3.UptimeCheckConfig() config.display_name = display_name or "New GET uptime check" config.monitored_resource = { "type": "uptime_url", "labels": {"host": host_name or "example.com"}, } config.http_check = { "request_method": monitoring_v3.UptimeCheckConfig.HttpCheck.RequestMethod.GET, "path": "/", ``` -------------------------------- ### Install Ruby Client Library Source: https://docs.cloud.google.com/monitoring/docs/reference/libraries Install the Ruby client library for Cloud Monitoring using gem. ```ruby gem install google-cloud-monitoring ``` -------------------------------- ### List Alert Policies using C++ Client Library Source: https://docs.cloud.google.com/monitoring/docs/reference/libraries This C++ example shows how to list alert policies for a given project using the Cloud Monitoring client library. Ensure you have the necessary dependencies installed. ```C++ #include "google/cloud/monitoring/v3/alert_policy_client.h" #include "google/cloud/project.h" #include int main(int argc, char* argv[]) try { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " project-id\n"; return 1; } namespace monitoring = ::google::cloud::monitoring_v3; auto client = monitoring::AlertPolicyServiceClient( monitoring::MakeAlertPolicyServiceConnection()); auto const project = google::cloud::Project(argv[1]); for (auto a : client.ListAlertPolicies(project.FullName())) { if (!a) throw std::move(a).status(); std::cout << a->DebugString() << "\n"; } return 0; } catch (google::cloud::Status const& status) { std::cerr << "google::cloud::Status thrown: " << status << "\n"; return 1; } ``` -------------------------------- ### Install C# Client Library Source: https://docs.cloud.google.com/monitoring/docs/reference/libraries Use the Package Manager Console in Visual Studio to install the C# client library for Cloud Monitoring. ```csharp Install-Package Google.Cloud.Monitoring.V3 -Pre ``` -------------------------------- ### Install Node.js Client Library Source: https://docs.cloud.google.com/monitoring/docs/reference/libraries Install the Node.js client library for Cloud Monitoring using npm. ```javascript npm install @google-cloud/monitoring ``` -------------------------------- ### Install Python Client Library Source: https://docs.cloud.google.com/monitoring/docs/reference/libraries Upgrade the Python client library for Cloud Monitoring using pip. ```python pip install --upgrade google-cloud-monitoring ``` -------------------------------- ### Get Uptime Check Configuration in Go Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-uptime-check-get Fetches an uptime check configuration using its resource name. This example requires setting up Application Default Credentials for authentication. ```go // get is an example of getting an uptime check. resourceName should be // of the form `projects/[PROJECT_ID]/uptimeCheckConfigs/[UPTIME_CHECK_ID]`. func get(w io.Writer, resourceName string) (*monitoringpb.UptimeCheckConfig, error) { ctx := context.Background() client, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { return nil, fmt.Errorf("NewUptimeCheckClient: %w", err) } defer client.Close() req := &monitoringpb.GetUptimeCheckConfigRequest{ Name: resourceName, } config, err := client.GetUptimeCheckConfig(ctx, req) if err != nil { return nil, fmt.Errorf("GetUptimeCheckConfig: %w", err) } fmt.Fprintf(w, "Config: %v", config) return config, nil } ``` -------------------------------- ### Get Monitored Resource Descriptor in Python Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-get-resource Fetches and prints details of a monitored resource descriptor. This example requires Application Default Credentials to be configured. ```python from google.cloud import monitoring_v3 def get_monitored_resource(project_id: str, resource_type: str): """Gets information about a monitored resource descriptor. Args: project_id: The Google Cloud project ID. resource_type: The type of the monitored resource (e.g., "gce_instance"). """ client = monitoring_v3.MetricServiceClient() name = client.monitored_resource_descriptor_path( project_id, resource_type ) response = client.get_monitored_resource_descriptor(name=name) print(f"Name: {response.name}") print(f"Type: {response.type}") print(f"Display Name: {response.display_name}") print(f"Description: {response.description}") print("Labels:") for label in response.labels: print(f" {label.key} ({label.value_type}) - {label.description}") # Example usage: # get_monitored_resource("your-project-id", "gcs_bucket") ``` -------------------------------- ### Example Monitored Resource Source: https://docs.cloud.google.com/monitoring/docs/monitoring-overview Shows the structure of the 'resource' field, which identifies the monitored hardware or software component. ```json "resource": { "type": "gce_instance", "labels": { "instance_id": "2708613220420473591", "zone": "us-east1-b", "project_id": "sampleproject" } } ``` -------------------------------- ### Example Log Scope Entries Source: https://docs.cloud.google.com/monitoring/docs/setup-application-monitoring Illustrates the format of entries within a configured log scope, showing log views and associated projects. ```text _Default/_AllLogs my-folder-mp _Default/_AllLogs project-in-my-folder _Default/_AllLogs another-project-in-my-folder ``` -------------------------------- ### Create Custom Metric Descriptor in Go Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-create-metric This Go sample demonstrates creating a custom metric descriptor. It requires the `cloud.google.com/go/monitoring/apiv3` package and proper authentication setup. ```go import ( "context" "fmt" "io" monitoring "cloud.google.com/go/monitoring/apiv3" "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" "google.golang.org/genproto/googleapis/api/label" "google.golang.org/genproto/googleapis/api/metric" metricpb "google.golang.org/genproto/googleapis/api/metric" ) // createCustomMetric creates a custom metric specified by the metric type. func createCustomMetric(w io.Writer, projectID, metricType string) (*metricpb.MetricDescriptor, error) { ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { return nil, err } defer c.Close() md := &metric.MetricDescriptor{ Name: "Custom Metric", Type: metricType, Labels: []*label.LabelDescriptor{{ Key: "environment", ValueType: label.LabelDescriptor_STRING, Description: "An arbitrary measurement", }}, MetricKind: metric.MetricDescriptor_GAUGE, ValueType: metric.MetricDescriptor_INT64, Unit: "s", Description: "An arbitrary measurement", DisplayName: "Custom Metric", } req := &monitoringpb.CreateMetricDescriptorRequest{ Name: "projects/" + projectID, MetricDescriptor: md, } m, err := c.CreateMetricDescriptor(ctx, req) if err != nil { return nil, fmt.Errorf("could not create custom metric: %w", err) } fmt.Fprintf(w, "Created %s\n", m.GetName()) return m, nil } ``` -------------------------------- ### Create Alert Policy (Go) Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-alert-create-channel Demonstrates how to create an alert policy using the Go client library. Ensure Application Default Credentials are set up for authentication. ```go if _, err = alertClient.CreateAlertPolicy(ctx, req); err != nil { log.Fatal(err) } } } fmt.Fprintf(w, "Successfully restored alerts.") return nil } ``` -------------------------------- ### Get Uptime Check Configuration in Node.js Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-uptime-check-get Retrieves an uptime check configuration using its full resource name. This example requires the `@google-cloud/monitoring` library and authenticated credentials. ```javascript // Imports the Google Cloud client library const monitoring = require('@google-cloud/monitoring'); // Creates a client const client = new monitoring.UptimeCheckServiceClient(); /** * TODO(developer): Uncomment and edit the following lines of code. */ // const projectId = 'YOUR_PROJECT_ID'; // const uptimeCheckConfigId = 'YOUR_UPTIME_CHECK_CONFIG_ID'; const request = { // i.e. name: 'projects/my-project-id/uptimeCheckConfigs/My-Uptime-Check name: client.projectUptimeCheckConfigPath(projectId, uptimeCheckConfigId), }; console.log(`Retrieving ${request.name}`); // Retrieves an uptime check config const [uptimeCheckConfig] = await client.getUptimeCheckConfig(request); console.log(`ID: ${uptimeCheckConfig.name}`); console.log(`Display Name: ${uptimeCheckConfig.displayName}`); console.log('Resource: %j', uptimeCheckConfig.monitoredResource); console.log('Period: %j', uptimeCheckConfig.period); console.log('Timeout: %j', uptimeCheckConfig.timeout); console.log(`Check type: ${uptimeCheckConfig.check_request_type}`); console.log( 'Check: %j', uptimeCheckConfig.httpCheck || uptimeCheckConfig.tcpCheck ); console.log( `Content matchers: ${uptimeCheckConfig.contentMatchers .map(matcher => matcher.content) .join(', ')}` ); console.log(`Regions: ${uptimeCheckConfig.selectedRegions.join(', ')}`); ``` -------------------------------- ### Get Monitored Resource Descriptor (Python) Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-get-resource Retrieves a monitored resource descriptor by its project and resource type name. Requires the `google-cloud-monitoring` library and proper authentication setup (Application Default Credentials). ```python from google.cloud import monitoring_v3 client = monitoring_v3.MetricServiceClient() resource_path = ( f"projects/{project_id}/monitoredResourceDescriptors/{resource_type_name}" ) descriptor = client.get_monitored_resource_descriptor(name=resource_path) pprint.pprint(descriptor) ``` -------------------------------- ### Write Time Series Data using Go Client Library Source: https://docs.cloud.google.com/monitoring/docs/reference/libraries This Go example demonstrates writing a data point for a custom metric to Cloud Monitoring. It requires setting up your Google Cloud project ID and importing necessary packages. ```Go // Sample monitoring-quickstart writes a data point to Stackdriver Monitoring. package main import ( "context" "fmt" "log" "time" monitoring "cloud.google.com/go/monitoring/apiv3/v2" "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" googlepb "github.com/golang/protobuf/ptypes/timestamp" metricpb "google.golang.org/genproto/googleapis/api/metric" monitoredrespb "google.golang.org/genproto/googleapis/api/monitoredres" ) func main() { ctx := context.Background() // Creates a client. client, err := monitoring.NewMetricClient(ctx) if err != nil { log.Fatalf("Failed to create client: %v", err) } // Sets your Google Cloud Platform project ID. projectID := "YOUR_PROJECT_ID" // Prepares an individual data point dataPoint := &monitoringpb.Point{ Interval: &monitoringpb.TimeInterval{ EndTime: &googlepb.Timestamp{ Seconds: time.Now().Unix(), }, }, Value: &monitoringpb.TypedValue{ Value: &monitoringpb.TypedValue_DoubleValue{ DoubleValue: 123.45, }, }, } // Writes time series data. if err := client.CreateTimeSeries(ctx, &monitoringpb.CreateTimeSeriesRequest{ Name: fmt.Sprintf("projects/%s", projectID), TimeSeries: []*monitoringpb.TimeSeries{ { Metric: &metricpb.Metric{ Type: "custom.googleapis.com/stores/daily_sales", Labels: map[string]string{ "store_id": "Pittsburg", }, }, Resource: &monitoredrespb.MonitoredResource{ ``` -------------------------------- ### List Uptime Check IPs in Go Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-uptime-check-list-ips Lists uptime check IPs using the Go client library. Requires setting up Application Default Credentials. Handles potential errors during client creation and iteration. ```go // listIPs is an example of listing uptime check IPs. func listIPs(w io.Writer) error { ctx := context.Background() client, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { return fmt.Errorf("NewUptimeCheckClient: %w", err) } defer client.Close() req := &monitoringpb.ListUptimeCheckIpsRequest{} it := client.ListUptimeCheckIps(ctx, req) for { config, err := it.Next() if err == iterator.Done { break } if err != nil { return fmt.Errorf("ListUptimeCheckIps: %w", err) } fmt.Fprintln(w, config) } fmt.Fprintln(w, "Done listing uptime check IPs") return nil } ``` -------------------------------- ### List Uptime Check Configurations (Python) Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-uptime-check-list-configs Lists all uptime check configurations for a specified project. Ensure Application Default Credentials are set up for authentication. ```python client = monitoring_v3.UptimeCheckServiceClient() configs = client.list_uptime_check_configs(request={"parent": project_id}) for config in configs: pprint.pprint(config) return configs ``` -------------------------------- ### Create GET Uptime Check (Go) Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-uptime-check-create Creates an uptime check that performs an HTTP GET request using the Cloud Monitoring API in Go. Requires setting up Application Default Credentials. ```go // createGet creates an example uptime check on a GET request. func createGet(w io.Writer, projectID string) (*monitoringpb.UptimeCheckConfig, error) { ctx := context.Background() client, err := monitoring.NewUptimeCheckClient(ctx) if err != nil { return nil, fmt.Errorf("NewUptimeCheckClient: %w", err) } defer client.Close() req := &monitoringpb.CreateUptimeCheckConfigRequest{ Parent: "projects/" + projectID, UptimeCheckConfig: &monitoringpb.UptimeCheckConfig{ DisplayName: "new GET uptime check", Resource: &monitoringpb.UptimeCheckConfig_MonitoredResource{ MonitoredResource: &monitoredres.MonitoredResource{ Type: "uptime_url", Labels: map[string]string{ "host": "example.com", }, }, }, CheckRequestType: &monitoringpb.UptimeCheckConfig_HttpCheck_ { HttpCheck: &monitoringpb.UptimeCheckConfig_HttpCheck{ RequestMethod: monitoringpb.UptimeCheckConfig_HttpCheck_GET, Path: "/", Port: 80, }, }, Timeout: &duration.Duration{Seconds: 10}, Period: &duration.Duration{Seconds: 300}, }, } config, err := client.CreateUptimeCheckConfig(ctx, req) if err != nil { return nil, fmt.Errorf("CreateUptimeCheckConfig GET: %w", err) } fmt.Fprintf(w, "Successfully created GET uptime check %q\n", config.GetDisplayName()) return config, nil } ``` -------------------------------- ### Example Metric Field Source: https://docs.cloud.google.com/monitoring/docs/monitoring-overview Demonstrates the 'metric' field, which specifies what is being measured and includes relevant labels. ```json "metric": { "labels": { "instance_name": "test" }, "type": "compute.googleapis.com/instance/cpu/utilization" }, ``` -------------------------------- ### Initialize Alert Policy Service Client (PHP) Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-alert-backup-policies Initializes the Alert Policy Service Client for a given project ID. This is a prerequisite for performing operations like listing alert policies. ```php use Google\Cloud\Monitoring\V3\Client\AlertPolicyServiceClient; use Google\Cloud\Monitoring\V3\Client\NotificationChannelServiceClient; use Google\Cloud\Monitoring\V3\ListAlertPoliciesRequest; use Google\Cloud\Monitoring\V3\ListNotificationChannelsRequest; /** * Back up alert policies. * * @param string $projectId Your project ID */ function alert_backup_policies($projectId) { $alertClient = new AlertPolicyServiceClient([ 'projectId' => $projectId, ]); ``` -------------------------------- ### List Metric Descriptors in Go Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-list-descriptors Lists all available metric descriptors for a given project using the Go client library. Ensure Application Default Credentials are set up for authentication. The output is written to the provided io.Writer. ```go import ( "context" "fmt" "io" monitoring "cloud.google.com/go/monitoring/apiv3" "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" "google.golang.org/api/iterator" ) // listMetrics lists all the metrics available to be monitored in the API. func listMetrics(w io.Writer, projectID string) error { ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { return err } defer c.Close() req := &monitoringpb.ListMetricDescriptorsRequest{ Name: "projects/" + projectID, } iter := c.ListMetricDescriptors(ctx, req) for { resp, err := iter.Next() if err == iterator.Done { break } if err != nil { return fmt.Errorf("Could not list metrics: %w", err) } fmt.Fprintf(w, "%v\n", resp.GetType()) } fmt.Fprintln(w, "Done") return nil } ``` -------------------------------- ### Example Time Series Points Source: https://docs.cloud.google.com/monitoring/docs/monitoring-overview Illustrates the structure of the 'points' array within a time series, containing timestamped measurements. ```json "points": [ { "interval": { "startTime": "2020-07-27T20:20:21.597143Z", "endTime": "2020-07-27T20:20:21.597143Z" }, "value": { "doubleValue": 0.473005 } }, { "interval": { "startTime": "2020-07-27T20:19:21.597239Z", "endTime": "2020-07-27T20:19:21.597239Z" }, "value": { "doubleValue": 0.473025 } }, ], ``` -------------------------------- ### Get Metric Descriptor in PHP Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-get-descriptor Retrieves a metric descriptor using the PHP client library. Requires Application Default Credentials. ```php use Google\Cloud\Monitoring\V3\Client\MetricServiceClient; use Google\Cloud\Monitoring\V3\GetMetricDescriptorRequest; /** * Example: * ``` * get_descriptor($projectId); * ``` * * @param string $projectId Your project ID * @param string $metricId The ID of the Metric Descriptor to get */ function get_descriptor($projectId, $metricId) { $metrics = new MetricServiceClient([ 'projectId' => $projectId, ]); $metricName = $metrics->metricDescriptorName($projectId, $metricId); $getMetricDescriptorRequest = (new GetMetricDescriptorRequest()) ->setName($metricName); $descriptor = $metrics->getMetricDescriptor($getMetricDescriptorRequest); printf('Name: ' . $descriptor->getDisplayName() . PHP_EOL); } ``` -------------------------------- ### Initialize Google Cloud CLI Source: https://docs.cloud.google.com/monitoring/docs/custom-constraints Initializes the gcloud CLI. This command is necessary before using other gcloud commands. ```bash gcloud init ``` -------------------------------- ### Get Monitored Resource Descriptor in Java Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-get-resource Retrieves a monitored resource descriptor and prints its details. Ensure Application Default Credentials are configured. ```java void getMonitoredResource(String resourceId) throws IOException { String projectId = System.getProperty("projectId"); try (final MetricServiceClient client = MetricServiceClient.create();) { MonitoredResourceDescriptorName name = MonitoredResourceDescriptorName.of(projectId, resourceId); MonitoredResourceDescriptor response = client.getMonitoredResourceDescriptor(name); System.out.println("Retrieved Monitored Resource: " + gson.toJson(response)); } } ``` -------------------------------- ### Get Monitored Resource Descriptor in C# Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-get-resource Retrieves and prints details of a monitored resource descriptor. Ensure Application Default Credentials are set up. ```csharp public static object GetMonitoredResource(string projectId, string resourceId) { MetricServiceClient client = MetricServiceClient.Create(); MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName(projectId, resourceId); var response = client.GetMonitoredResourceDescriptor(name); string resource = JObject.Parse($"{response}").ToString(); Console.WriteLine($"{ resource }"); return 0; } ``` -------------------------------- ### Python: Initialize MetricServiceClient and Project Name Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-read-timeseries-reduce Initializes the Google Cloud Monitoring MetricServiceClient and defines the project name for subsequent API calls. ```python from google.cloud import monitoring_v3 client = monitoring_v3.MetricServiceClient() project_name = f"projects/{project_id}" now = time.time() seconds = int(now) ``` -------------------------------- ### Get Metric Descriptor in Java Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-get-descriptor Retrieves a metric descriptor using the Java client library. Ensure Application Default Credentials are configured. ```java // Your Google Cloud Platform project ID final String projectId = System.getProperty("projectId"); MetricDescriptorName descriptorName = MetricDescriptorName.of(projectId, type); try (final MetricServiceClient client = MetricServiceClient.create();) { MetricDescriptor response = client.getMetricDescriptor(descriptorName); System.out.println("Printing metrics descriptor: " + response); } ``` -------------------------------- ### List Alert Policies in Go Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-alert-list-policies Lists alert policies in a specified project using the Google Cloud Monitoring client library for Go. Requires setting up Application Default Credentials. ```go // listAlertPolicies lists the alert policies in the project. func listAlertPolicies(w io.Writer, projectID string) error { ctx := context.Background() client, err := monitoring.NewAlertPolicyClient(ctx) if err != nil { return err } defer client.Close() req := &monitoringpb.ListAlertPoliciesRequest{ Name: "projects/" + projectID, // Filter: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering. // OrderBy: "", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering. } it := client.ListAlertPolicies(ctx, req) for { resp, err := it.Next() if err == iterator.Done { fmt.Fprintln(w, "Done") break } if err != nil { return err } fmt.Fprintf(w, " Name: %q\n", resp.GetName()) fmt.Fprintf(w, " Display Name: %q\n", resp.GetDisplayName()) fmt.Fprintf(w, " Documentation Content: %q\n\n", resp.GetDocumentation().GetContent()) } return nil } ``` -------------------------------- ### Write Time Series Data (Go) Source: https://docs.cloud.google.com/monitoring/docs/reference/libraries Demonstrates how to write time series data using the Go client library. Ensure the client is closed after use to flush data. ```go package main import ( "context" "log" monitoring "cloud.google.com/go/monitoring/apiv3" "cloud.google.com/go/monitoring/apiv3/monitoringpb" "time" ) func main() { ctx := context.Background() // TODO(developer): Set projectID and dataPoint before running the sample. var projectID string var dataPoint *monitoringpb.Point client, err := monitoring.NewMetricClient(ctx) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer client.Close() // Write time series data. if _, err := client.CreateTimeSeries(ctx, &monitoringpb.CreateTimeSeriesRequest{ Name: monitoringpb.ProjectName(projectID).String(), TimeSeries: []*monitoringpb.TimeSeries{ { Metric: &monitoringpb.Metric{ Type: "custom.googleapis.com/stores/daily_sales", Labels: map[string]string{ "store_id": "San Francisco", }, }, Resource: &monitoringpb.MonitoredResource{ Type: "global", Labels: map[string]string{ "project_id": projectID, }, }, Points: []*monitoringpb.Point{ dataPoint, }, }, }, }); err != nil { log.Fatalf("Failed to write time series data: %v", err) } // Closes the client and flushes the data to Stackdriver. if err := client.Close(); err != nil { log.Fatalf("Failed to close client: %v", err) } fmt.Printf("Done writing time series data.\n") } ``` -------------------------------- ### Delete Notification Channel in Java Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-alert-delete-channel Deletes a notification channel. This example uses `NotificationChannelName.of` to construct the channel name and `deleteNotificationChannel` to perform the deletion. ```java static void deleteNotificationChannel(String channelName) throws IOException { String projectId = System.getProperty("projectId"); try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) { NotificationChannelName name = NotificationChannelName.of(projectId, channelName); client.deleteNotificationChannel(channelName, false); System.out.println("Deleted notification channel " + channelName); } } ``` -------------------------------- ### List Monitored Resources in Go Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-list-resources Lists monitored resource descriptors for a project. Requires the 'cloud.google.com/go/monitoring' package and Application Default Credentials. ```go import ( "context" "fmt" "io" "log" monitoring "cloud.google.com/go/monitoring/apiv3" "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" "google.golang.org/api/iterator" ) // listMonitoredResources lists all the resources available to be monitored. func listMonitoredResources(w io.Writer, projectID string) error { ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { return err } defer c.Close() req := &monitoringpb.ListMonitoredResourceDescriptorsRequest{ Name: "projects/" + projectID, } iter := c.ListMonitoredResourceDescriptors(ctx, req) for { resp, err := iter.Next() if err == iterator.Done { break } if err != nil { return fmt.Errorf("Could not list time series: %w", err) } fmt.Fprintf(w, "%v\n", resp) } fmt.Fprintln(w, "Done") return nil } func main() { // Example usage: Replace "your-project-id" with your actual project ID. projectID := "your-project-id" if err := listMonitoredResources(log.Writer(), projectID); err != nil { log.Fatalf("Failed to list monitored resources: %v", err) } } ``` -------------------------------- ### Get Monitored Resource Descriptor in Go Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-get-resource Fetches and prints information about a monitored resource descriptor, including its name, description, type, and labels. Requires setting up Application Default Credentials. ```go import ( "context" "fmt" "io" monitoring "cloud.google.com/go/monitoring/apiv3" "cloud.google.com/go/monitoring/apiv3/v2/monitoringpb" ) // getMonitoredResource gets the descriptor for the given resourceType and // prints information about it. resource should be of the form // "projects/[PROJECT_ID]/monitoredResourceDescriptors/[RESOURCE_TYPE]". func getMonitoredResource(w io.Writer, resource string) error { ctx := context.Background() c, err := monitoring.NewMetricClient(ctx) if err != nil { return fmt.Errorf("NewMetricClient: %w", err) } defer c.Close() req := &monitoringpb.GetMonitoredResourceDescriptorRequest{ Name: resource, } resp, err := c.GetMonitoredResourceDescriptor(ctx, req) if err != nil { return fmt.Errorf("could not get custom metric: %w", err) } fmt.Fprintf(w, "Name: %v\n", resp.GetName()) fmt.Fprintf(w, "Description: %v\n", resp.GetDescription()) fmt.Fprintf(w, "Type: %v\n", resp.GetType()) fmt.Fprintf(w, "Labels:\n") for _, l := range resp.GetLabels() { fmt.Fprintf(w, "\t%s (%s) - %s", l.GetKey(), l.GetValueType(), l.GetDescription()) } return nil } ``` -------------------------------- ### Get Uptime Check Configuration in C# Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-uptime-check-get Retrieves a specific uptime check configuration by its name. Ensure you have authenticated using Application Default Credentials. ```csharp public static object GetUptimeCheckConfig(string configName) { var client = UptimeCheckServiceClient.Create(); UptimeCheckConfig config = client.GetUptimeCheckConfig(configName); if (config == null) { Console.Error.WriteLine( "No configuration found with the name {0}", configName); return -1; } Console.WriteLine("Name: {0}", config.Name); Console.WriteLine("Display Name: {0}", config.DisplayName); Console.WriteLine("Http Path: {0}", config.HttpCheck.Path); return 0; } ``` -------------------------------- ### Get Metric Descriptor (Python) Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-get-descriptor Retrieves and pretty-prints a metric descriptor using the Python client library. Requires Application Default Credentials for authentication. ```python client = monitoring_v3.MetricServiceClient() descriptor = client.get_metric_descriptor(name=metric_name) pprint.pprint(descriptor) ``` -------------------------------- ### Write Time Series Data using C# Client Library Source: https://docs.cloud.google.com/monitoring/docs/reference/libraries This C# example demonstrates how to write a data point for a custom metric to Cloud Monitoring. It requires setting up your Google Cloud project ID and ensuring the necessary using directives are present. ```C# using System; using System.Collections.Generic; using Google.Cloud.Monitoring.V3; using Google.Protobuf.WellKnownTypes; using Google.Api; using Google.Api.Gax.ResourceNames; namespace GoogleCloudSamples { public class QuickStart { public static void Main(string[] args) { // Your Google Cloud Platform project ID. string projectId = "YOUR-PROJECT-ID"; // Create client. MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s). ProjectName name = new ProjectName(projectId); // Prepare a data point. TypedValue salesTotal = new TypedValue { DoubleValue = 123.45 }; Point dataPoint = new Point { Value = salesTotal }; // Sets data point's interval end time to current time. DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); Timestamp timeStamp = new Timestamp { Seconds = (long)(DateTime.UtcNow - UnixEpoch).TotalSeconds }; TimeInterval interval = new TimeInterval { EndTime = timeStamp }; dataPoint.Interval = interval; // Prepare custom metric. Metric metric = new Metric { Type = "custom.googleapis.com/my_metric" }; metric.Labels.Add("store_id", "Pittsburgh"); // Prepare monitored resource. MonitoredResource resource = new MonitoredResource { Type = "gce_instance" }; resource.Labels.Add("project_id", projectId); resource.Labels.Add("instance_id", "1234567890123456789"); resource.Labels.Add("zone", "us-central1-f"); // Create a new time series using inputs. TimeSeries timeSeriesData = new TimeSeries { Metric = metric, Resource = resource }; timeSeriesData.Points.Add(dataPoint); // Add newly created time series to list of time series to be written. IEnumerable timeSeries = new List { timeSeriesData }; // Write time series data. metricServiceClient.CreateTimeSeries(name, timeSeries); Console.WriteLine("Done writing time series data."); } } } ``` -------------------------------- ### Get Uptime Check Configuration in Ruby Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-uptime-check-get Retrieves an uptime check configuration using the Ruby client library. Ensure Application Default Credentials are configured. ```ruby gem "google-cloud-monitoring" require "google/cloud/monitoring" def get_uptime_check_config config_name client = Google::Cloud::Monitoring.uptime_check_service config = client.get_uptime_check_config name: config_name pp config.to_h config end ``` -------------------------------- ### List Uptime Check Configurations in Java Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-uptime-check-list-configs Retrieves and prints the display names of all uptime check configurations for a given project. Includes error handling for exceptions during the process. ```java private static void listUptimeChecks(String projectId) throws IOException { ListUptimeCheckConfigsRequest request = ListUptimeCheckConfigsRequest.newBuilder().setParent(ProjectName.format(projectId)).build(); try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) { ListUptimeCheckConfigsPagedResponse response = client.listUptimeCheckConfigs(request); for (UptimeCheckConfig config : response.iterateAll()) { System.out.println(config.getDisplayName()); } } catch (Exception e) { usage("Exception listing uptime checks: " + e.toString()); throw e; } } ``` -------------------------------- ### Get Uptime Check Configuration in Python Source: https://docs.cloud.google.com/monitoring/docs/samples/monitoring-uptime-check-get Fetches an uptime check configuration by its name using the Python client library. Requires Application Default Credentials. ```python def get_uptime_check_config(config_name: str) -> uptime.UptimeCheckConfig: """Reads the uptime check configuration Args: config_name: Uptime check configuration identity Returns: A structure that describes the updated uptime check """ client = monitoring_v3.UptimeCheckServiceClient() config = client.get_uptime_check_config(request={"name": config_name}) pprint.pprint(config) return config ```