Configurazione su Google Kubernetes Engine

Puoi inviare gli errori delle applicazioni Google Kubernetes Engine a Error Reporting in due modi:

Utilizzare Logging per segnalare gli errori

L'agente di logging predefinito di GKE fornisce una soluzione gestita per eseguire il deployment e gestire gli agenti che inviano i log dei cluster a Cloud Logging. La struttura dell'agente dipende dalla versione del cluster. Per informazioni su questo agente, consulta Gestire i log di GKE.

Error Reporting richiede che le eccezioni o le analisi dello stack siano contenute in una singola voce di log. La maggior parte degli agenti di logging è in grado di riconoscere che più righe di log (i frame dello stack stampati ciascuno su una nuova riga) rappresentano un'analisi dello stack e di inviarla a Cloud Logging come una singola voce di log. Se l'agente non è in grado di ricostruire più righe come un singolo errore, allora utilizza l'endpoint API projects.events.report, che ti consente di controllare i contenuti di un errore.

Utilizzare l'API Error Reporting per scrivere gli errori

L'API Error Reporting fornisce un endpoint report per scrivere le informazioni sugli errori nel servizio.

  1. Abilita l'API Error Reporting.

    Ruoli richiesti per abilitare le API

    Per abilitare le API, devi disporre del ruolo IAM Amministratore utilizzo servizi (roles/serviceusage.serviceUsageAdmin), che contiene l'autorizzazione serviceusage.services.enable. Scopri come concedere i ruoli.

    Abilita l'API

  2. Segnala gli errori all'API utilizzando l'API REST o una libreria client.

Esempi

ASP.NET

Il pacchetto NuGet ASP.NET segnala le eccezioni non rilevate dalle applicazioni web ASP.NET a Error Reporting.

Installare il pacchetto NuGet

Per installare il pacchetto NuGet Stackdriver ASP.NET in Visual Studio:

  1. Fai clic con il tasto destro del mouse sulla soluzione e seleziona Gestisci pacchetti NuGet per la soluzione.
  2. Seleziona la casella di controllo Includi versione preliminare.
  3. Cerca e installa il pacchetto denominato Google.Cloud.Diagnostics.AspNet.

Utilizzo

Dopo aver installato il pacchetto NuGet Stackdriver ASP.NET, aggiungi la seguente istruzione al codice dell'applicazione per iniziare a inviare gli errori a Stackdriver:

using Google.Cloud.Diagnostics.AspNet;

Aggiungi il seguente HttpConfiguration codice al Register metodo della tua app web .NET dopo aver sostituito your-project-id con l'ID progetto effettivo per abilitare la segnalazione delle eccezioni:

public static void Register(HttpConfiguration config)
{
    string projectId = "YOUR-PROJECT-ID";
    string serviceName = "NAME-OF-YOUR-SERVICE";
    string version = "VERSION-OF-YOUR-SERVCICE";
    // ...
    // Add a catch all for the uncaught exceptions.
    config.Services.Add(typeof(IExceptionLogger),
        ErrorReportingExceptionLogger.Create(projectId, serviceName, version));
    // ...
}

Dopo aver aggiunto questo metodo all'applicazione ASP.NET, puoi visualizzare le eccezioni non rilevate che si verificano quando vengono segnalate Google Cloud nella sezione Error Reporting della Google Cloud console.

C#

Il seguente esempio è disponibile nel repository GoogleCloudPlatform/dotnet-docs-samples. Per utilizzarlo, dopo aver creato il progetto, specifica il tuo ID progetto:

C:\...\bin\Debug> set GOOGLE_PROJECT_ID=[YOUR_PROJECT_ID]

Assicurati di sostituire [YOUR_PROJECT_ID] con il valore corretto della Google Cloud console.

Quindi, invia i dati delle eccezioni con un codice simile al seguente:

public class ErrorReportingSample
{
    public static void Main(string[] args)
    {
        try
        {
            throw new Exception("Generic exception for testing Stackdriver Error Reporting");
        }
        catch (Exception e)
        {
            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>
    private static ClouderrorreportingService CreateErrorReportingClient()
    {
        // Get the Application Default Credentials.
        GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;

        // Add the needed scope to the credentials.
        credential.CreateScoped(ClouderrorreportingService.Scope.CloudPlatform);

        // Create the Error Reporting Service.
        ClouderrorreportingService service = new ClouderrorreportingService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
        });
        return service;
    }

    /// <summary>
    /// Creates a <seealso cref="ReportRequest"/> from a given exception.
    /// </summary>
    private static ReportRequest CreateReportRequest(Exception e)
    {
        // Create the service.
        ClouderrorreportingService service = CreateErrorReportingClient();

        // Get the project ID from the environement variables.
        string projectId = 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/report
        string formattedProjectId = 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#ServiceContext
        ServiceContext serviceContext = new ServiceContext()
        {
            Service = "myapp",
            Version = "8c1917a9eca3475b5a3686d1d44b52908463b989",
        };
        ReportedErrorEvent errorEvent = new ReportedErrorEvent()
        {
            Message = e.ToString(),
            ServiceContext = serviceContext,
        };
        return new ReportRequest(service, errorEvent, formattedProjectId);
    }

    /// <summary>
    /// Report an exception to the Error Reporting service.
    /// </summary>
    private static void report(Exception e)
    {
        // Create the report and execute the request.
        ReportRequest request = CreateReportRequest(e);
        request.Execute();
    }
}

Go

Consulta Configurare Error Reporting per Go.

Java

Consulta Configurare Error Reporting per Java.

Node.js

Consulta Configurare Error Reporting per Node.js.

Ruby

Consulta Configurare Error Reporting per Ruby.

Python

Consulta Configurare Error Reporting per Python.

PHP

Consulta Configurare Error Reporting per PHP.

Visualizzare i gruppi di errori

Nella Google Cloud console, vai alla pagina Error Reporting:

Vai a Error Reporting

Puoi trovare questa pagina anche utilizzando la barra di ricerca.