El agente de registro predeterminado de GKE proporciona una solución administrada para implementar y administrar los agentes que envían los registros de los clústeres a Cloud Logging. La estructura del agente depende de la versión del clúster. Para obtener información sobre este agente, consulta Administra los registros de GKE.
Error Reporting requiere que las excepciones o los seguimientos de pila se incluyan en una sola entrada de registro. La mayoría de los agentes de Logging pueden reconocer que varias líneas de registro (marcos de pila impresos cada uno en una línea nueva) representan un seguimiento de pila y lo envían a Cloud Logging como una sola entrada de registro.
Si el agente no puede reconstruir varias líneas como un solo error, usa el extremo de la API de projects.events.report, que te permite controlar el contenido de un error.
Usa la API de Error Reporting para escribir errores
La API de Error Reporting proporciona un extremo report para escribir información de error en el servicio.
El paquete NuGet de ASP.NET informa sobre excepciones no detectadas de las aplicaciones web de ASP.NET a Error Reporting.
Instala el paquete NuGet
Para instalar el paquete Stackdriver ASP.NET NuGet en Visual Studio, haz lo siguiente:
Haz clic derecho en la solución y selecciona Administrar paquetes NuGet para la solución.
Selecciona la casilla de verificación Incluir lanzamiento anticipado.
Busca y, luego, instala el paquete llamado Google.Cloud.Diagnostics.AspNet.
Uso
Una vez que hayas instalado el paquete Stackdriver ASP.NET NuGet, agrega la siguiente declaración al código de tu aplicación para comenzar a enviar errores a Stackdriver:
using Google.Cloud.Diagnostics.AspNet;
Agrega el siguiente código HttpConfiguration al método Register de tu aplicación web .NET; para ello, reemplaza your-project-id por tu ID del proyecto real a fin de permitir el informe de excepciones:
publicstaticvoidRegister(HttpConfigurationconfig){stringprojectId="YOUR-PROJECT-ID";stringserviceName="NAME-OF-YOUR-SERVICE";stringversion="VERSION-OF-YOUR-SERVCICE";// ...// Add a catch all for the uncaught exceptions.config.Services.Add(typeof(IExceptionLogger),ErrorReportingExceptionLogger.Create(projectId,serviceName,version));// ...}
Una vez que hayas agregado este método a tu aplicación ASP.NET, podrás ver las excepciones no detectadas que se produzcan a medida que se informen a Google Clouden la sección Error Reporting de la consola de Google Cloud .
Asegúrate de reemplazar [YOUR_PROJECT_ID] por el valor correcto de la consola deGoogle Cloud .
Luego, envía datos de excepciones con un código similar al siguiente:
publicclassErrorReportingSample{publicstaticvoidMain(string[]args){try{thrownewException("Generic exception for testing Stackdriver Error Reporting");}catch(Exceptione){report(e);Console.WriteLine("Stackdriver Error Report Sent");}}/// <summary>/// Create the Error Reporting service (<seealso cref="ClouderrorreportingService"/>)/// with the Application Default Credentials and the proper scopes./// See: https://developers.google.com/identity/protocols/application-default-credentials./// </summary>privatestaticClouderrorreportingServiceCreateErrorReportingClient(){// Get the Application Default Credentials.GoogleCredentialcredential=GoogleCredential.GetApplicationDefaultAsync().Result;// Add the needed scope to the credentials.credential.CreateScoped(ClouderrorreportingService.Scope.CloudPlatform);// Create the Error Reporting Service.ClouderrorreportingServiceservice=newClouderrorreportingService(newBaseClientService.Initializer{HttpClientInitializer=credential,});returnservice;}/// <summary>/// Creates a <seealso cref="ReportRequest"/> from a given exception./// </summary>privatestaticReportRequestCreateReportRequest(Exceptione){// Create the service.ClouderrorreportingServiceservice=CreateErrorReportingClient();// Get the project ID from the environement variables.stringprojectId=Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");// Format the project id to the format Error Reporting expects. See:// https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events/reportstringformattedProjectId=string.Format("projects/{0}",projectId);// Add a service context to the report. For more details see:// https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events#ServiceContextServiceContextserviceContext=newServiceContext(){Service="myapp",Version="8c1917a9eca3475b5a3686d1d44b52908463b989",};ReportedErrorEventerrorEvent=newReportedErrorEvent(){Message=e.ToString(),ServiceContext=serviceContext,};returnnewReportRequest(service,errorEvent,formattedProjectId);}/// <summary>/// Report an exception to the Error Reporting service./// </summary>privatestaticvoidreport(Exceptione){// Create the report and execute the request.ReportRequestrequest=CreateReportRequest(e);request.Execute();}}
[[["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"]],["Última actualización: 2025-09-03 (UTC)"],[[["\u003cp\u003eGKE applications can send errors to Error Reporting through Cloud Logging or by using the Error Reporting API.\u003c/p\u003e\n"],["\u003cp\u003eWhen using Cloud Logging, ensure that log entries containing exceptions or stack traces are formatted as single log entries for proper recognition by Error Reporting.\u003c/p\u003e\n"],["\u003cp\u003eThe Error Reporting API allows error reporting via REST API calls or through experimental client libraries available in various languages such as ASP.NET, Go, Java, Node.js, Ruby, Python, and PHP.\u003c/p\u003e\n"],["\u003cp\u003eThe Error Reporting API provides a \u003ccode\u003ereport\u003c/code\u003e endpoint, and client libraries such as the ASP.NET NuGet package, include specific setup instructions within their documentation to integrate with the service.\u003c/p\u003e\n"],["\u003cp\u003eThe Error Reporting page in the Google Cloud console allows users to view reported error groups and requires prior setup to function properly.\u003c/p\u003e\n"]]],[],null,["You can send errors from your Google Kubernetes Engine applications to\nError Reporting in one of two ways:\n\n- [By logging to Cloud Logging](#using_logging). If you're already using\n Cloud Logging, the only additional requirement is that your log entries be\n recognizable by Error Reporting. For more information\n on error formatting requirements, read\n [Formatting errors in Cloud Logging](/error-reporting/docs/formatting-error-messages).\n\n- [Using the Error Reporting API](#using_the_api). Your application\n can send HTTP requests using the REST API, or can make use of\n experimental libraries in several languages.\n\nUsing Logging to report errors\n\nGKE's default logging agent provides a managed solution to\ndeploy and manage the agents that send the logs for your clusters to\nCloud Logging. The structure of the agent depends on the version of the\ncluster. For information about this agent, see\n[Managing GKE logs](/stackdriver/docs/solutions/gke/managing-logs).\n\nError Reporting requires that exceptions or stack traces be contained\nin a single log entry. Most logging agents are capable of recognizing that\nseveral log lines---stack frames printed each on a new line---represent\na stack trace and send it to Cloud Logging as a single log entry.\nIf the agent isn't capable of reconstructing multiple lines as a single error,\nthen use the\n[`projects.events.report` API endpoint](/error-reporting/reference/rest/v1beta1/projects.events/report),\nwhich allows you to control the contents of an error.\n\nUsing the Error Reporting API to write errors\n\nThe Error Reporting API provides a `report` endpoint for writing\nerror information to the service.\n\n1.\n\n\n Enable the Error Reporting API.\n\n\n [Enable the API](https://console.cloud.google.com/flows/enableapi?apiid=clouderrorreporting.googleapis.com)\n\n \u003cbr /\u003e\n\n2. Report errors to the API using either the REST API or a client library.\n\n - REST API\n\n See the\n [reference documentation](/error-reporting/reference/rest/v1beta1/projects.events/report)\n for information about the API.\n - Using client libraries\n\n Libraries exist in a limited number of languages to help you call\n the Error Reporting API from your application:\n - [ASP.NET](/error-reporting/docs/setup/dotnet)\n - [Go](/error-reporting/docs/setup/go)\n - [Java](/error-reporting/docs/setup/java)\n - [Node.js](/error-reporting/docs/setup/nodejs)\n - [Ruby](/error-reporting/docs/setup/ruby)\n - [Python](/error-reporting/docs/setup/python)\n - [PHP](/error-reporting/docs/setup/php)\n\nSamples \n\nASP.NET\n\nThe ASP.NET NuGet package reports uncaught exceptions from\nASP.NET web applications to Error Reporting.\n\nInstall the NuGet package\n\nTo install the Stackdriver ASP.NET NuGet package in Visual Studio:\n\n1. Right-click your solution and select **Manage NuGet packages for\n solution**.\n2. Select the **Include prerelease** checkbox.\n3. Search for and install the package named `Google.Cloud.Diagnostics.AspNet`.\n\nUsage\n\nOnce you've installed the Stackdriver ASP.NET NuGet package, add the\nfollowing statement to your application code to start sending errors to\nStackdriver: \n\n using Google.Cloud.Diagnostics.AspNet;\n\nAdd the following `HttpConfiguration` code to the `Register` method of your\n.NET web app (replacing `your-project-id` with your actual\n[project ID](https://support.google.com/cloud/answer/6158840?hl=en)\nto enable the reporting of exceptions: \n\n public static void Register(HttpConfiguration config)\n {\n string projectId = \"YOUR-PROJECT-ID\";\n string serviceName = \"NAME-OF-YOUR-SERVICE\";\n string version = \"VERSION-OF-YOUR-SERVCICE\";\n // ...\n // Add a catch all for the uncaught exceptions.\n config.Services.Add(typeof(IExceptionLogger),\n ErrorReportingExceptionLogger.Create(projectId, serviceName, version));\n // ...\n }\n\nOnce you've added this method to your ASP.NET application, you can view any\nuncaught exceptions that occur as they get reported to Google Cloud\nin the [Error Reporting](https://console.cloud.google.com/errors)\nsection of the Google Cloud console.\n\nC#\n\nThe following example can be found in the\n[GoogleCloudPlatform/dotnet-docs-samples](https://github.com/GoogleCloudPlatform/dotnet-docs-samples/tree/vs2015)\nrepo. To use it, after building the project, specify your\n[project ID](https://support.google.com/cloud/answer/6158840?hl=en): \n\n C:\\...\\bin\\Debug\u003e set GOOGLE_PROJECT_ID=[YOUR_PROJECT_ID]\n\nMake sure to replace `[YOUR_PROJECT_ID]` with the correct value from the\nGoogle Cloud console.\n\nThen, send exception data with code similar to the following: \n\n public class ErrorReportingSample\n {\n public static void Main(string[] args)\n {\n try\n {\n throw new Exception(\"Generic exception for testing Stackdriver Error Reporting\");\n }\n catch (Exception e)\n {\n report(e);\n Console.WriteLine(\"Stackdriver Error Report Sent\");\n }\n }\n\n /// \u003csummary\u003e\n /// Create the Error Reporting service (\u003cseealso cref=\"ClouderrorreportingService\"/\u003e)\n /// with the Application Default Credentials and the proper scopes.\n /// See: https://developers.google.com/identity/protocols/application-default-credentials.\n /// \u003c/summary\u003e\n private static ClouderrorreportingService CreateErrorReportingClient()\n {\n // Get the Application Default Credentials.\n GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;\n\n // Add the needed scope to the credentials.\n credential.CreateScoped(ClouderrorreportingService.Scope.CloudPlatform);\n\n // Create the Error Reporting Service.\n ClouderrorreportingService service = new ClouderrorreportingService(new BaseClientService.Initializer\n {\n HttpClientInitializer = credential,\n });\n return service;\n }\n\n /// \u003csummary\u003e\n /// Creates a \u003cseealso cref=\"ReportRequest\"/\u003e from a given exception.\n /// \u003c/summary\u003e\n private static ReportRequest CreateReportRequest(Exception e)\n {\n // Create the service.\n ClouderrorreportingService service = CreateErrorReportingClient();\n\n // Get the project ID from the environement variables.\n string projectId = Environment.GetEnvironmentVariable(\"GOOGLE_PROJECT_ID\");\n\n // Format the project id to the format Error Reporting expects. See:\n // https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events/report\n string formattedProjectId = string.Format(\"projects/{0}\", projectId);\n\n // Add a service context to the report. For more details see:\n // https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events#ServiceContext\n ServiceContext serviceContext = new ServiceContext()\n {\n Service = \"myapp\",\n Version = \"8c1917a9eca3475b5a3686d1d44b52908463b989\",\n };\n ReportedErrorEvent errorEvent = new ReportedErrorEvent()\n {\n Message = e.ToString(),\n ServiceContext = serviceContext,\n };\n return new ReportRequest(service, errorEvent, formattedProjectId);\n }\n\n /// \u003csummary\u003e\n /// Report an exception to the Error Reporting service.\n /// \u003c/summary\u003e\n private static void report(Exception e)\n {\n // Create the report and execute the request.\n ReportRequest request = CreateReportRequest(e);\n request.Execute();\n }\n }\n\nGo\n\nSee [Setting up Error Reporting for Go](/error-reporting/docs/setup/go).\n\nJava\n\nSee [Setting up Error Reporting for Java](/error-reporting/docs/setup/java).\n\nNode.js\n\nSee [Setting up Error Reporting for Node.js](/error-reporting/docs/setup/nodejs).\n\nRuby\n\nSee [Setting up Error Reporting for Ruby](/error-reporting/docs/setup/ruby).\n\nPython\n\nSee [Setting up Error Reporting for Python](/error-reporting/docs/setup/python).\n\nPHP\n\nSee [Setting up Error Reporting for PHP](/error-reporting/docs/setup/php).\n\nView error groups\n\nIn the Google Cloud console, go to the **Error Reporting** page:\n\n[Go to **Error Reporting**](https://console.cloud.google.com/errors)\n\n\u003cbr /\u003e\n\nYou can also find this page by using the search bar.\n\n\u003cbr /\u003e\n\n| **Note** : If you see the message \"Set up Error Reporting\" on the **Error Reporting** page, then your Google Cloud project has no error groups to display.\n\n\u003cbr /\u003e"]]