简体   繁体   中英

How to setup Stackdriver Error Reporting on Play Framework 1.4

I am running a Play Framework 1.4 app on Heroku. My goal is to capture any Java exception in my production application and report it to Stackdriver Error Reporting for automatic exception monitoring and alerting.

In the Google Cloud Console , create a new project if needed, then enable the Stackdriver Error Reporting API and get an API key .

Then the goal is to use the simple Stackdriver Error Reporting report API endpoint : send error stack traces using an HTTP POST request and an API key.

Instrument the Play Framework application to catch all exceptions, format them in the expected structure and POST them to Stackdriver (make sure you are using at least JDK v1.7).

Here is the code you need to add to the application controller:

public class Application extends Controller {

@Catch(value={Exception.class})
public static void onException(Exception ex) {
    StringWriter exceptionWriter = new StringWriter();
    ex.printStackTrace(new PrintWriter(exceptionWriter));

    Map<String, Object> payload = new HashMap<String, Object>();
    payload.put("message", exceptionWriter.toString());
    Map<String,String> serviceContextData = new HashMap<String, String>();
    serviceContextData.put("service", "randomgift");
    payload.put("serviceContext", serviceContextData);
    Gson gson = new Gson();
    String payloadStr = gson.toJson(payload); 

    Map<String, String> headers = new HashMap<String,String>();
    headers.put("Content-Type", "application/json");

    // Report to Stackdriver Error Reporting:
    String apikey = "<your-api-key>";
    String projectName = "<your-project-id>";
    WS.url("https://clouderrorreporting.googleapis.com/v1beta1/projects/" + projectName + "/events:report?key=" + apikey)
      .headers(headers)
      .body(payloadStr)
      .post();

    Logger.info("Error reported");
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM