Configurazione di Error Reporting su Amazon EC2

Puoi inviare gli errori dalle tue applicazioni EC2 a Error Reporting in due modi:

Utilizzare Logging per segnalare gli errori

Per connettere le tue applicazioni EC2 a Error Reporting, invia le eccezioni o altri errori a Logging.

Ecco alcuni esempi:

  1. Connettere il sistema Amazon Web Services (AWS) a Google Cloud. Per saperne di più, consulta Installazione dell'agente Logging su singole VM.
  2. Installa l'agente Logging google-fluentd appropriato per il tuo ambiente. Per le istruzioni, consulta Installazione dell'agente Logging.
  3. Modificare l'applicazione in modo che registri le eccezioni e le analisi dello stack in Logging.

    Devi includere tutte le informazioni relative a un singolo errore o eccezione nella stessa voce di log, inclusi tutti i frame di qualsiasi analisi dello stack. Se tutte le informazioni non sono possibili, Error Reporting potrebbe non rilevare l'errore. Puoi utilizzare il formato JSON strutturato per i payload voce di log in modo da includere diversi tipi di informazioni per ogni errore.

  4. Java

    Aggiungi quanto segue al tuo file pom.xml:

    <dependency>
      <groupId>org.fluentd</groupId>
      <artifactId>fluent-logger</artifactId>
      <version>0.3.4</version>
    </dependency>

    Per inviare i dati delle eccezioni, utilizza il codice riportato di seguito:

    public class ExceptionUtil {
      private static FluentLogger ERRORS = FluentLogger.getLogger("myapp");
    
      public static void main(String[] args) {
        try {
          throw new Exception("Generic exception for testing Stackdriver");
        } catch (Exception e) {
          report(e);
        }
      }
    
      public static void report(Throwable ex) {
        StringWriter exceptionWriter = new StringWriter();
        ex.printStackTrace(new PrintWriter(exceptionWriter));
        Map<String, Object> data = new HashMap<>();
        data.put("message", exceptionWriter.toString());
        Map<String, String> serviceContextData = new HashMap<>();
        serviceContextData.put("service", "myapp");
        data.put("serviceContext", serviceContextData);
        // ... add more metadata
        ERRORS.log("errors", data);
      }
    }

    Python

    Innanzitutto, installa la libreria fluent-logger-python:

    sudo pip install fluent-logger
    

    Per inviare i dati delle eccezioni, utilizza il codice riportato di seguito:

    import traceback
    
    import fluent.event
    import fluent.sender
    
    def simulate_error():
        fluent.sender.setup("myapp", host="localhost", port=24224)
    
        def report(ex):
            data = {}
            data["message"] = "{0}".format(ex)
            data["serviceContext"] = {"service": "myapp"}
            # ... add more metadata
            fluent.event.Event("errors", data)
    
        # report exception data using:
        try:
            # simulate calling a method that's not defined
            raise NameError
        except Exception:
            report(traceback.format_exc())
    
    

    Node.js

    Innanzitutto, installa la libreria fluent-logger-node:

    npm install --save fluent-logger
    

    Per inviare i dati delle eccezioni, utilizza il codice riportato di seguito:

    const structuredLogger = require('fluent-logger').createFluentSender('myapp', {
      host: 'localhost',
      port: 24224,
      timeout: 3.0,
    });
    
    const report = (err, req) => {
      const payload = {
        serviceContext: {
          service: 'myapp',
        },
        message: err.stack,
        context: {
          httpRequest: {
            url: req.originalUrl,
            method: req.method,
            referrer: req.header('Referer'),
            userAgent: req.header('User-Agent'),
            remoteIp: req.ip,
            responseStatusCode: 500,
          },
        },
      };
      structuredLogger.emit('errors', payload);
    };
    
    // Handle errors (the following uses the Express framework)
    // eslint-disable-next-line no-unused-vars
    app.use((err, req, res, next) => {
      report(err, req);
      res.status(500).send(err.response || 'Something broke!');
    });

    Go

    Innanzitutto, installa il pacchetto fluent-logger-golang:

    go get github.com/fluent/fluent-logger-golang/
    

    Utilizza quindi il codice come segue per inviare dati di errore:

    
    package main
    
    import (
    	"log"
    	"net/http"
    	"os"
    	"runtime"
    
    	"github.com/fluent/fluent-logger-golang/fluent"
    )
    
    var logger *fluent.Fluent
    
    func main() {
    	var err error
    	logger, err = fluent.New(fluent.Config{
    		FluentHost: "localhost",
    		FluentPort: 24224,
    	})
    	if err != nil {
    		log.Fatal(err)
    	}
    
    	http.HandleFunc("/demo", demoHandler)
    
    	port := os.Getenv("PORT")
    	if port == "" {
    		port = "8080"
    	}
    	log.Printf("Listening on port %s", port)
    	if err := http.ListenAndServe(":"+port, nil); err != nil {
    		log.Fatal(err)
    	}
    }
    
    func report(stackTrace string, r *http.Request) {
    	payload := map[string]interface{}{
    		"serviceContext": map[string]interface{}{
    			"service": "myapp",
    		},
    		"message": stackTrace,
    		"context": map[string]interface{}{
    			"httpRequest": map[string]interface{}{
    				"method":    r.Method,
    				"url":       r.URL.String(),
    				"userAgent": r.UserAgent(),
    				"referrer":  r.Referer(),
    				"remoteIp":  r.RemoteAddr,
    			},
    		},
    	}
    	if err := logger.Post("myapp.errors", payload); err != nil {
    		log.Print(err)
    	}
    }
    
    // Handler for the incoming requests.
    func demoHandler(w http.ResponseWriter, r *http.Request) {
    	// How to handle a panic.
    	defer func() {
    		if e := recover(); e != nil {
    			stack := make([]byte, 1<<16)
    			stackSize := runtime.Stack(stack, true)
    			report(string(stack[:stackSize]), r)
    		}
    	}()
    
    	// Panic is triggered.
    	x := 0
    	log.Println(100500 / x)
    }
    

    Utilizzo dell'API Error Reporting per scrivere errori

    L'API Error Reporting fornisce un endpoint report per la scrittura delle informazioni sugli errori nel servizio.

    1. Attiva l'API Error Reporting.

      Abilita l'API

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

    Esempi

    ASP.NET

    I report sui pacchetti ASP.NET NuGet non individuati presentano eccezioni provenienti dalle applicazioni web ASP.NET a Error Reporting.

    Installa il pacchetto NuGet

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

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

    Utilizzo

    Una volta installato il pacchetto Cloud Get ASP.NET di Stackdriver, aggiungi la seguente istruzione al codice dell'applicazione per iniziare a inviare gli errori a Stackdriver:

    using Google.Cloud.Diagnostics.AspNet;
    

    Aggiungi il codice HttpConfiguration seguente al metodo Register della tua app web .NET (sostituendo your-project-id con l'ID progetto effettivo per abilitare la generazione di report sulle 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 tutte le eccezioni non rilevate che si verificano durante la segnalazione a Google Cloud nella sezione Error Reporting della console Google Cloud.

    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 nella console Google Cloud.

    Invia poi i dati delle eccezioni con 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

    Vedi Configurazione di Error Reporting per Go.

    Java

    Consulta la sezione Configurazione di Error Reporting per Java.

    Node.js

    Vedi Configurazione di Error Reporting per Node.js.

    Ruby

    Vedi Configurazione di Error Reporting per Ruby.

    Python

    Vedi Configurazione di Error Reporting per Python.

    PHP

    Vedi Configurare Error Reporting per PHP.

    Visualizza gruppi di errori

    Nella console Google Cloud, seleziona Error Reporting o fai clic sul pulsante seguente, quindi seleziona un progetto:

    Vai a Error Reporting