Mostrar lista de políticas de alertas
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Muestra cómo enumerar políticas de alertas.
Explora más
Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:
Muestra de código
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],[],[],[],null,["# List alerting policies\n\nDemonstrates how to list alerting policies.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Manage alerting policies by API](/monitoring/alerts/using-alerting-api)\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n static void ListAlertPolicies(string projectId)\n {\n var client = AlertPolicyServiceClient.Create();\n var response = client.ListAlertPolicies(new ProjectName(projectId));\n foreach (AlertPolicy policy in response)\n {\n Console.WriteLine(policy.Name);\n if (policy.DisplayName != null)\n {\n Console.WriteLine(policy.DisplayName);\n }\n if (policy.Documentation?.Content != null)\n {\n Console.WriteLine(policy.Documentation.Content);\n }\n Console.WriteLine();\n }\n }\n\n### Go\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n\n // listAlertPolicies lists the alert policies in the project.\n func listAlertPolicies(w io.Writer, projectID string) error {\n \tctx := context.Background()\n \tclient, err := monitoring.NewAlertPolicyClient(ctx)\n \tif err != nil {\n \t\treturn err\n \t}\n \tdefer client.Close()\n\n \treq := &monitoringpb.ListAlertPoliciesRequest{\n \t\tName: \"projects/\" + projectID,\n \t\t// Filter: \"\", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.\n \t\t// OrderBy: \"\", // See https://cloud.google.com/monitoring/api/v3/sorting-and-filtering.\n \t}\n \tit := client.ListAlertPolicies(ctx, req)\n \tfor {\n \t\tresp, err := it.Next()\n \t\tif err == iterator.Done {\n \t\t\tfmt.Fprintln(w, \"Done\")\n \t\t\tbreak\n \t\t}\n \t\tif err != nil {\n \t\t\treturn err\n \t\t}\n \t\tfmt.Fprintf(w, \" Name: %q\\n\", resp.GetName())\n \t\tfmt.Fprintf(w, \" Display Name: %q\\n\", resp.GetDisplayName())\n \t\tfmt.Fprintf(w, \" Documentation Content: %q\\n\\n\", resp.GetDocumentation().GetContent())\n \t}\n \treturn nil\n }\n\n### Java\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n private static void listAlertPolicies(String projectId) throws IOException {\n try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {\n ListAlertPoliciesPagedResponse response = client.listAlertPolicies(ProjectName.of(projectId));\n\n System.out.println(\"Alert Policies:\");\n for (AlertPolicy policy : response.iterateAll()) {\n System.out.println(\n String.format(\"\\nPolicy %s\\nalert-id: %s\", policy.getDisplayName(), policy.getName()));\n int channels = policy.getNotificationChannelsCount();\n if (channels \u003e 0) {\n System.out.println(\"notification-channels:\");\n for (int i = 0; i \u003c channels; i++) {\n System.out.println(\"\\t\" + policy.getNotificationChannels(i));\n }\n }\n if (policy.hasDocumentation() && policy.getDocumentation().getContent() != null) {\n System.out.println(policy.getDocumentation().getContent());\n }\n }\n }\n }\n\n### Node.js\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n // Imports the Google Cloud client library\n const monitoring = require('https://cloud.google.com/nodejs/docs/reference/monitoring/latest/overview.html');\n\n // Creates a client\n const client = new monitoring.https://cloud.google.com/nodejs/docs/reference/monitoring/latest/overview.html();\n\n async function listPolicies() {\n /**\n * TODO(developer): Uncomment the following lines before running the sample.\n */\n // const projectId = 'YOUR_PROJECT_ID';\n\n const listAlertPoliciesRequest = {\n name: client.projectPath(projectId),\n };\n const [policies] = await client.listAlertPolicies(listAlertPoliciesRequest);\n console.log('Policies:');\n policies.forEach(policy =\u003e {\n console.log(` Display name: ${policy.displayName}`);\n if (policy.documentation && policy.documentation.content) {\n console.log(` Documentation: ${policy.documentation.content}`);\n }\n });\n }\n listPolicies();\n\n### PHP\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n use Google\\Cloud\\Monitoring\\V3\\Client\\AlertPolicyServiceClient;\n use Google\\Cloud\\Monitoring\\V3\\ListAlertPoliciesRequest;\n\n /**\n * Adds a new column to the Albums table in the example database.\n * Example:\n * ```\n * alert_list_policies($projectId);\n * ```\n *\n * @param string $projectId Your project ID\n */\n function alert_list_policies($projectId)\n {\n $projectName = 'projects/' . $projectId;\n $alertClient = new AlertPolicyServiceClient([\n 'projectId' =\u003e $projectId,\n ]);\n $listAlertPoliciesRequest = (new ListAlertPoliciesRequest())\n -\u003esetName($projectName);\n\n $policies = $alertClient-\u003elistAlertPolicies($listAlertPoliciesRequest);\n foreach ($policies-\u003eiterateAllElements() as $policy) {\n printf('Name: %s (%s)' . PHP_EOL, $policy-\u003egetDisplayName(), $policy-\u003egetName());\n }\n }\n\n### Python\n\n\nTo authenticate to Monitoring, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n def list_alert_policies(project_name):\n \"\"\"List alert policies in a project.\n\n Arguments:\n project_name (str): The Google Cloud Project to use. The project name\n must be in the format - 'projects/\u003cPROJECT_NAME\u003e'.\n \"\"\"\n\n client = monitoring_v3.AlertPolicyServiceClient()\n policies = client.list_alert_policies(name=project_name)\n print(\n str(\n tabulate.tabulate(\n [(policy.name, policy.display_name) for policy in policies],\n (\"name\", \"display_name\"),\n )\n )\n )\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=monitoring)."]]