הגדרה ב-Compute Engine

יש שתי דרכים לשלוח שגיאות מהאפליקציות שלכם ב-Compute Engine אל Error Reporting:

שימוש ברישום ביומן כדי לדווח על שגיאות

כדי לקשר את האפליקציות של Compute Engine אל Error Reporting, צריך לשלוח את החריגים או שגיאות אחרות אל Logging.

לדוגמה:

  1. מתקינים את סוכן הרישום google-fluentd בהתאם לסביבה שלכם. הוראות מפורטות מופיעות במאמר בנושא התקנת סוכן Logging.
  2. משנים את האפליקציה כך שהיא תתעד חריגים ואת עקבות המחסנית שלהם ב-Logging.

    צריך לכלול את כל המידע לגבי שגיאה או חריג אחד באותה רשומה ביומן, כולל כל המסגרות של כל דוח קריסות. אם כל המידע לא נמצא ביחד, יכול להיות שהתכונה 'דיווח על שגיאות' לא תזהה את השגיאה. אתם יכולים להשתמש בפורמט JSON מובנה עבור מטען הייעודי (payload) של רשומות ביומן כדי לכלול סוגים שונים של מידע לכל שגיאה.

Java

מוסיפים לקובץ pom.xml את הנתונים הבאים:

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

לאחר מכן משתמשים בקוד כמו זה שבהמשך כדי לשלוח את נתוני החריגה:

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

קודם כול, מתקינים את ספריית fluent-logger-python:

sudo pip install fluent-logger

לאחר מכן משתמשים בקוד כמו זה שבהמשך כדי לשלוח את נתוני החריגה:

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

קודם כול, מתקינים את ספריית fluent-logger-node:

npm install fluent-logger

לאחר מכן משתמשים בקוד כמו זה שבהמשך כדי לשלוח את נתוני החריגה:

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!');
});

המשך

קודם כול, מתקינים את חבילת fluent-logger-golang:

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

אחר כך משתמשים בקוד כמו זה שבהמשך כדי לשלוח נתוני שגיאות:


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)
}

שימוש ב-Error Reporting API כדי לכתוב שגיאות

‫Error Reporting API מספק נקודת קצה report לכתיבת מידע על שגיאות לשירות.

  1. מפעילים את Error Reporting API.

    תפקידים שנדרשים להפעלת ממשקי API

    כדי להפעיל ממשקי API, צריך את תפקיד ה-IAM 'אדמין של Service Usage' (roles/serviceusage.serviceUsageAdmin), שכולל את ההרשאה serviceusage.services.enable. איך מקצים תפקידים

    להפעלת ה-API

  2. אפשר לדווח על שגיאות ל-API באמצעות API בארכיטקטורת REST או ספריית לקוח.

    • ‫API בארכיטקטורת REST

      מידע על ה-API מופיע במאמרי העזרה.

    • שימוש בספריות לקוח

      קיימות ספריות במספר מוגבל של שפות שיעזרו לכם לקרוא ל-Error Reporting API מהאפליקציה:

דוגמאות

ASP.NET

חבילת ה-NuGet של ASP.NET מדווחת על חריגים שלא זוהו מאפליקציות אינטרנט של ASP.NET אל Error Reporting.

התקנת חבילת NuGet

כדי להתקין את חבילת Stackdriver ASP.NET NuGet ב-Visual Studio:

  1. לוחצים לחיצה ימנית על הפתרון ובוחרים באפשרות Manage NuGet packages for solution (ניהול חבילות NuGet לפתרון).
  2. מסמנים את תיבת הסימון Include prerelease (הכללת גרסת טרום-הפצה).
  3. מחפשים את החבילה בשם Google.Cloud.Diagnostics.AspNet ומתקינים אותה.

Usage

אחרי שמתקינים את חבילת Stackdriver ASP.NET NuGet, מוסיפים את ההצהרה הבאה לקוד האפליקציה כדי להתחיל לשלוח שגיאות ל-Stackdriver:

using Google.Cloud.Diagnostics.AspNet;

כדי להפעיל את הדיווח על חריגים, מוסיפים את הקוד HttpConfiguration הבא לשיטה Register של אפליקציית האינטרנט שלכם ב-‎.NET אחרי שמחליפים את your-project-id במזהה הפרויקט בפועל:

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));
    // ...
}

אחרי שמוסיפים את השיטה הזו לאפליקציית ASP.NET, אפשר לראות את כל החריגים שלא נתפסו שמתרחשים בזמן שהם מדווחים ל- Google Cloudבקטע Error Reporting במסוף Google Cloud .

C#‎

הדוגמה הבאה מופיעה במאגר GoogleCloudPlatform/dotnet-docs-samples. כדי להשתמש בו, אחרי שיוצרים את הפרויקט, מציינים את מזהה הפרויקט:

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

חשוב להקפיד להחליף את [YOUR_PROJECT_ID] בערך הנכון מהמסוףGoogle Cloud .

לאחר מכן, שולחים נתוני חריגים באמצעות קוד שדומה לקוד הבא:

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();
    }
}

המשך

הגדרת Error Reporting ל-Go

Java

הוראות להגדרת Error Reporting ב-Java

Node.js

הגדרת Error Reporting ל-Node.js

Ruby

אפשר לקרוא על הגדרת Error Reporting עבור Ruby.

Python

הוראות להגדרת Error Reporting ב-Python

PHP

הגדרת Error Reporting ל-PHP

הצגת קבוצות של שגיאות

נכנסים לדף Error Reporting במסוף Google Cloud :

עבור אל Error Reporting

אפשר גם להשתמש בסרגל החיפוש כדי למצוא את הדף הזה.