הגדרת מעקב באפליקציות Java לצורך דיווח על שגיאות

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

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

השירות Error Reporting משולב עם חלק מהשירותים, כמו פונקציות של Cloud Run, ‏ App Engine, ‏ Compute Engine ו-Google Kubernetes Engine. Google Cloud ב-Error Reporting מוצגים אירועי השגיאות שנרשמים ב-Cloud Logging על ידי אפליקציות שפועלות בשירותים האלה. מידע נוסף זמין בקטע הפעלה ב Google Cloud בדף הזה.

אפשר גם לשלוח אירועי שגיאה אל Error Reporting באמצעות Logging. במאמר פורמט של רשומה ביומן לדיווח על אירועי שגיאה מוסבר על הדרישות בנוגע לפורמט הנתונים.

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Error Reporting API .

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Error Reporting API .

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the API

התקנת ספריית הלקוח

חבילת Error Reporting ל-Java מאפשרת לכם לעקוב אחרי אירועי שגיאה שדווחו על ידי אפליקציות Java שפועלות כמעט בכל מקום, ולצפות בהם.

    אם משתמשים ב-Maven, צריך להוסיף את הקוד הבא לקובץ pom.xml. במאמר העוסק בספריות BOM ל-Google Cloud Platform תוכלו לקרוא מידע נוסף על עצי מוצרים (BOM).

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.83.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-errorreporting</artifactId>
      </dependency>
    </dependencies>

    אם משתמשים ב-Gradle, צריך להוסיף את הקוד הבא ליחסי התלות:

    implementation 'com.google.cloud:google-cloud-errorreporting:0.214.0-beta'

    אם משתמשים ב-sbt, צריך להוסיף את הקוד הבא ליחסי התלות:

    libraryDependencies += "com.google.cloud" % "google-cloud-errorreporting" % "0.214.0-beta"

    אם משתמשים ב-Visual Studio Code או ב-IntelliJ, אפשר להוסיף את ספריות הלקוח לפרויקט באמצעות יישומי הפלאגין הבאים של IDE:

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

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

הגדרת ספריית הלקוח

אפשר להתאים אישית את ההתנהגות של חבילת Error Reporting ל-Java. מידע נוסף מופיע במאמרי העזרה של ה-API של Java.

הפעלת אפליקציות ב- Google Cloud

כדי ליצור קבוצות שגיאות באמצעות projects.events.report, לחשבון השירות שלכם נדרש התפקיד Error Reporting Writer (roles/errorreporting.writer).

חלק משירותי Google Cloud Google Cloud מעניקים באופן אוטומטי את התפקיד Error Reporting Writer ‏ (roles/errorreporting.writer) לחשבון השירות המתאים. עם זאת, בשביל שירותים מסוימים, צריך להעניק את התפקיד הזה לחשבון השירות המתאים.

פונקציות Cloud Run ו-Cloud Run

לחשבון השירות שמוגדר כברירת מחדל ב-Cloud Run יש את ההרשאות של התפקיד Error Reporting Writer (roles/errorreporting.writer).

אפשר להשתמש בחבילת Error Reporting ל-Java בלי לספק במפורש פרטי כניסה.

‫Cloud Run מוגדר לשימוש ב-Error Reporting באופן אוטומטי. חריגים שלא טופלו ב-JavaScript יופיעו ביומן וייעובדו על ידי Error Reporting בלי שתצטרכו להשתמש בחבילת Error Reporting ל-Java.

סביבה גמישה של App Engine

ב-App Engine, לחשבון השירות שמוגדר כברירת מחדל מוענק באופן אוטומטי התפקיד 'כתיבה ביומן' (roles/errorreporting.writer).

אפשר להשתמש בחבילת Error Reporting ל-Java בלי לספק במפורש פרטי כניסה.

הכלי Error Reporting מופעל באופן אוטומטי באפליקציות של סביבה גמישה ב-App Engine. לא נדרשת הגדרה נוספת.

@WebServlet(name = "Error reporting", value = "/error")
public class ErrorReportingExample extends HttpServlet {

  private Logger logger = Logger.getLogger(ErrorReportingExample.class.getName());

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {

    // errors logged to stderr / Cloud logging with exceptions are automatically reported.
    logger.log(Level.SEVERE, "exception using log framework", new IllegalArgumentException());

    // use the error-reporting client library only if you require logging custom error events.
    logCustomErrorEvent();

    // runtime exceptions are also automatically reported.
    throw new RuntimeException("this is a runtime exception");
  }

  private void logCustomErrorEvent() {
    try (ReportErrorsServiceClient reportErrorsServiceClient = ReportErrorsServiceClient.create()) {
      // Custom error events require an error reporting location as well.
      ErrorContext errorContext =
          ErrorContext.newBuilder()
              .setReportLocation(
                  SourceLocation.newBuilder()
                      .setFilePath("Test.java")
                      .setLineNumber(10)
                      .setFunctionName("myMethod")
                      .build())
              .build();
      // Report a custom error event
      ReportedErrorEvent customErrorEvent =
          ReportedErrorEvent.getDefaultInstance()
              .toBuilder()
              .setMessage("custom error event")
              .setContext(errorContext)
              .build();

      // default project id
      ProjectName projectName = ProjectName.of(ServiceOptions.getDefaultProjectId());
      reportErrorsServiceClient.reportErrorEvent(projectName, customErrorEvent);
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Exception encountered logging custom event", e);
    }
  }
}

Google Kubernetes Engine

כדי להשתמש ב-Error Reporting עם Google Kubernetes Engine, צריך לבצע את הפעולות הבאות:

  1. מוודאים שלחשבון השירות שבו ישתמש הקונטיינר הוקצה התפקיד 'כתיבה ב-Error Reporting' (roles/errorreporting.writer).

    אתם יכולים להשתמש בחשבון השירות שמוגדר כברירת מחדל ב-Compute Engine או בחשבון שירות מותאם אישית.

    מידע על הקצאת תפקידים מופיע במאמר ניהול הגישה לפרויקטים, לתיקיות ולארגונים.

  2. יוצרים את האשכול ומעניקים לאשכול את cloud-platform היקף הגישה.

    לדוגמה, בפקודת היצירה הבאה מצוינים היקף הגישה cloud-platform וחשבון שירות:

    gcloud container clusters create CLUSTER_NAME --service-account  SERVICE_ACCT_NAME --scopes=cloud-platform
    

Compute Engine

כדי להשתמש ב-Error Reporting עם מכונות וירטואליות ב-Compute Engine, צריך לבצע את הפעולות הבאות:

  1. מוודאים שלחשבון השירות שבו המכונה הווירטואלית משתמשת הוקצה התפקיד 'כותב דוחות שגיאות' (roles/errorreporting.writer).

    אתם יכולים להשתמש בחשבון השירות שמוגדר כברירת מחדל ב-Compute Engine או בחשבון שירות מותאם אישית.

    מידע על הקצאת תפקידים מופיע במאמר ניהול הגישה לפרויקטים, לתיקיות ולארגונים.

  2. נכנסים לדף VM instances במסוף Google Cloud :

    כניסה לדף VM instances

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

  3. בוחרים את מופע ה-VM שרוצים להעניק לו את cloud-platform היקף הגישה.

  4. לוחצים על עצירה ואז על עריכה.

  5. בקטע Identity and API access בוחרים חשבון שירות עם התפקיד Error Reporting Writer (roles/errorreporting.writer).

  6. בקטע Access scopes בוחרים באפשרות Allow full access to all Cloud APIs ושומרים את השינויים.

  7. לוחצים על התחלה/המשך.

דוגמה

חריגות שנרשמות ביומן באמצעות Cloud Logging Logback Appender או java.util.logging Handler מדווחות אוטומטית למסוף Error Reporting.

בדוגמה הבאה מוצג שימוש בספריית הלקוח של Java כדי לדווח על אירוע שגיאה בהתאמה אישית:

import com.google.cloud.ServiceOptions;
import com.google.devtools.clouderrorreporting.v1beta1.ProjectName;
import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorsServiceClient;
import com.google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Snippet demonstrates using the Error Reporting API to report an exception.
 * <p>
 * When the workload runs on App Engine, GKE, Cloud Functions or another managed environment,
 * printing the exception's stack trace to stderr will automatically report the error
 * to Error Reporting.
 */
public class QuickStart {

  static String projectId;

  public static void main(String[] args) throws Exception {
    // Set your Google Cloud Platform project ID via environment or explicitly
    projectId = ServiceOptions.getDefaultProjectId();
    if (args.length > 0) {
      projectId = args[0];
    } else {
      String value = System.getenv("GOOGLE_CLOUD_PROJECT");
      if (value != null && value.isEmpty()) {
        projectId = value;
      }
    }

    try {
      throw new Exception("Something went wrong");
    } catch (Exception ex) {
      reportError(ex);
    }
  }

  /**
   * Sends formatted error report to Google Cloud including the error context.
   *
   * @param ex Exception containing the error and the context.
   * @throws IOException if fails to communicate with Google Cloud
   */
  private static void reportError(Exception ex) throws IOException {
    try (ReportErrorsServiceClient serviceClient = ReportErrorsServiceClient.create()) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      ex.printStackTrace(pw);

      ReportedErrorEvent errorEvent = ReportedErrorEvent.getDefaultInstance()
          .toBuilder()
          .setMessage(sw.toString())
          .build();
      // If you need to report an error asynchronously, use reportErrorEventCallable()
      // method
      serviceClient.reportErrorEvent(ProjectName.of(projectId), errorEvent);
    }
  }
}

במאמרי העזרה של Java API מוסבר איך לאחזר ולנהל נתונים סטטיסטיים של שגיאות וגם נתונים של אירועים ספציפיים.

הרצת אפליקציות בסביבת פיתוח מקומית

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

כדי להשתמש בדוגמאות של Java שבדף הזה בסביבת פיתוח מקומית, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

  1. התקינו את ה-CLI של Google Cloud.

  2. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

  3. אם אתם משתמשים במעטפת מקומית, אתם צריכים ליצור פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

    אם מוחזרת שגיאת אימות ואתם משתמשים בספק זהויות חיצוני (IdP), ודאו ש נכנסתם ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

מפתחות API נתמכים גם על ידי projects.events.report method. אם אתם רוצים להשתמש במפתחות API לצורך אימות, לא צריך להגדיר קובץ מקומי של Application Default Credentials. מידע נוסף זמין במאמר בנושא יצירת מפתח API במסמכי האימות של Google Cloud .

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

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

עבור אל Error Reporting

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

מידע נוסף זמין במאמר בנושא הצגה וסינון של קבוצות שגיאות.