如何在 Java 中执行简单的 Google Cloud Trace 请求

How to do a simple Google Cloud Trace request in Java

我正在尝试对我的 Google Cloud Trace 项目执行简单的推送跟踪操作,但我似乎无法发送数据。

这是我的 build.gradle 文件:

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.oauth-client:google-oauth-client-java6:1.20.0'
    compile 'com.google.apis:google-api-services-cloudtrace:v1-rev6-1.22.0'
}

jar {
    from configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}

以及以下 Java 代码,其中包含项目 ID 和我的机密文件的虚拟信息:

package test;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudtrace.v1.CloudTrace;
import com.google.api.services.cloudtrace.v1.CloudTraceScopes;
import com.google.api.services.cloudtrace.v1.model.Trace;
import com.google.api.services.cloudtrace.v1.model.TraceSpan;
import com.google.api.services.cloudtrace.v1.model.Traces;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.time.Instant;
import java.util.Collections;

public class Test {

    public static void main(String[] args) throws IOException, GeneralSecurityException {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        GoogleCredential cred = GoogleCredential
                .fromStream(
                        new FileInputStream("/path/to/secrets.json"),
                        httpTransport,
                        jsonFactory)
                .createScoped(Collections.singletonList(CloudTraceScopes.TRACE_APPEND));

        CloudTrace gceTrace = new CloudTrace.Builder(httpTransport, jsonFactory, cred)
                .setApplicationName("Google Cloud Trace test app")
                .build();

        TraceSpan span1 = new TraceSpan();
        span1.setName("test");
        span1.setStartTime(Long.toString(Instant.now().toEpochMilli()*1000000)+"Z");
        Trace trace = new Trace();
        trace.setSpans(Collections.singletonList(span1));
        Traces traces = new Traces();
        traces.setTraces(Collections.singletonList(trace));
        gceTrace.projects().patchTraces("myprojectid", traces).execute();
    }

}

我目前收到以下错误,除了我的 startTime 值似乎有问题外,没有任何有用的指示:

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid value at 'traces.traces[0].spans[0].start_time' (type.googleapis.com/google.protobuf.Timestamp), Field 'startTime', Invalid time format: Failed to parse input",
    "reason" : "badRequest"
  } ],
  "message" : "Invalid value at 'traces.traces[0].spans[0].start_time' (type.googleapis.com/google.protobuf.Timestamp), Field 'startTime', Invalid time format: Failed to parse input",
  "status" : "INVALID_ARGUMENT"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.interceptResponse(AbstractGoogleClientRequest.java:321)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at test.Test.main(Test.java:44)

我尝试用以下值替换 startTime:

span1.setStartTime("2016-08-04T01:00:00Z");

这给了我:

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Request contains an invalid argument.",
    "reason" : "badRequest"
  } ],
  "message" : "Request contains an invalid argument.",
  "status" : "INVALID_ARGUMENT"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.interceptResponse(AbstractGoogleClientRequest.java:321)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at test.Test.main(Test.java:44)

我还尝试添加一个结束时间:

span1.setEndTime("2016-08-04T01:00:01Z");

这也给我同样的错误。

我几乎不知道需要做什么,因为我找不到一个可用的 Java 示例。 预先感谢您提供有效解决方案的任何指示。

终于想通了。这是一个工作示例,其中指出了必填字段和可选字段。

build.gradle

apply plugin: 'java'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.oauth-client:google-oauth-client-java6:1.20.0'
    compile 'com.google.apis:google-api-services-cloudtrace:v1-rev6-1.22.0'
}

jar {
    from configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
}

Test.java

package test;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.cloudtrace.v1.CloudTrace;
import com.google.api.services.cloudtrace.v1.CloudTraceScopes;
import com.google.api.services.cloudtrace.v1.model.Trace;
import com.google.api.services.cloudtrace.v1.model.TraceSpan;
import com.google.api.services.cloudtrace.v1.model.Traces;

import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Test {

    public static void main(String[] args) throws IOException, GeneralSecurityException {
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
        JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

        GoogleCredential cred = GoogleCredential
                .fromStream(
                        new FileInputStream("/path/to/secrets.json"),
                        httpTransport,
                        jsonFactory)
                .createScoped(Collections.singletonList(CloudTraceScopes.TRACE_APPEND));

        CloudTrace gceTrace = new CloudTrace.Builder(httpTransport, jsonFactory, cred)
                .setApplicationName("Google Cloud Trace test app")
                .build();

        // They are optional
        Map<String, String> labels = new HashMap<>();
        labels.put("key1", "val1");

        TraceSpan span = new TraceSpan();
        span.setSpanId(new BigInteger("1")); // Mandatory
        span.setName("test"); // Optional
        span.setKind("RPC_SERVER"); // Optional
        span.setStartTime("2016-08-04T01:00:00Z"); // Optional
        span.setEndTime("2016-08-04T01:00:01Z"); // Optional
        span.setLabels(labels); // Optional
        Trace trace = new Trace();
        trace.setProjectId("myprojectid"); // Mandatory
        trace.setTraceId("A096D4956A424EEB98AE7863505B1E1F"); // Mandatory
        trace.setSpans(Collections.singletonList(span)); // Mandatory
        Traces traces = new Traces();
        traces.setTraces(Collections.singletonList(trace)); // Mandatory
        gceTrace.projects().patchTraces("myprojectid", traces).execute();
    }

}

虽然有些值是可选的,例如 startTime 或 endTime,但将某些值放在那里是有意义的。

由于 this question 显示了预期值并查看了描述每个字段的 REST API 文档,我设法将其组合在一起,尤其是对于跟踪 ID 等神秘值: