简体   繁体   English

如何在Play Framework 1.4上设置Stackdriver Error Reporting

[英]How to setup Stackdriver Error Reporting on Play Framework 1.4

I am running a Play Framework 1.4 app on Heroku. 我在Heroku上运行Play Framework 1.4应用程序。 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. 我的目标是捕获生产应用程序中的任何Java异常,并将其报告给Stackdriver Error Reporting,以进行自动异常监视和警报。

In the Google Cloud Console , create a new project if needed, then enable the Stackdriver Error Reporting API and get an API key . Google Cloud Console中 ,根据需要创建一个新项目,然后启用S​​tackdriver Error Reporting API获取API密钥

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. 然后的目标是使用简单的Stackdriver Error Reporting 报告API端点 :使用HTTP POST请求和API密钥发送错误堆栈跟踪。

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). 对Play Framework应用程序进行检测,以捕获所有异常,将其格式化为所需的结构,然后将其发布到Stackdriver(确保您至少使用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");
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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