Java Code Examples for io.opentracing.mock.MockSpan#LogEntry

The following examples show how to use io.opentracing.mock.MockSpan#LogEntry . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StandardSpanDecoratorTest.java    From opentracing-toolbox with MIT License 6 votes vote down vote up
@Test
void shouldTagException() {
    final ResponseEntity<String> response = client
            .getForEntity("http://localhost:8080/exception", String.class);

    assertTrue(response.getStatusCode().is5xxServerError());

    final MockSpan span = span();
    final Map<String, Object> tags = span.tags();

    assertThat(tags, hasEntry("error", true));

    final List<MockSpan.LogEntry> logs = span.logEntries();
    assertThat(logs, hasSize(3));

    assertThat(logs.get(0).fields(), hasEntry(equalTo("message"),
            hasFeature(Objects::toString, containsString("Error"))));
    assertThat(logs.get(1).fields(),
            hasEntry("error.kind", "NestedServletException"));
    assertThat((Throwable) logs.get(1).fields().get("error.object"),
            hasFeature(Throwables::getRootCause,
                    instanceOf(UnsupportedOperationException.class)));
    assertThat(logs.get(2).fields(),
            hasEntry(equalTo("stack"), instanceOf(String.class)));
}
 
Example 2
Source File: TracingServerInterceptorTest.java    From java-grpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSpanFromHeaders() {
  long traceID = 1;
  long spanID = 2;
  MockTracer spyTracer = spy(serverTracer);
  doReturn(new MockSpan.MockContext(traceID, spanID, Collections.<String, String>emptyMap()))
      .when(spyTracer)
      .extract(eq(Format.Builtin.HTTP_HEADERS), any(TextMapAdapter.class));

  Span span =
      TracingServerInterceptor.newBuilder()
          .withTracer(spyTracer)
          .build()
          .getSpanFromHeaders(Collections.<String, String>emptyMap(), "operationName");
  assertNotNull("span is not null", span);
  MockSpan mockSpan = (MockSpan) span;
  assertEquals(
      "span parentID is set to extracted span context spanID", spanID, mockSpan.parentId());
  List<MockSpan.LogEntry> logEntries = mockSpan.logEntries();
  assertTrue("span contains no log entries", logEntries.isEmpty());
}
 
Example 3
Source File: TracingServerInterceptorTest.java    From java-grpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetSpanFromHeadersError() {
  MockTracer spyTracer = spy(serverTracer);
  doThrow(IllegalArgumentException.class)
      .when(spyTracer)
      .extract(eq(Format.Builtin.HTTP_HEADERS), any(TextMapAdapter.class));

  Span span =
      TracingServerInterceptor.newBuilder()
          .withTracer(spyTracer)
          .build()
          .getSpanFromHeaders(Collections.<String, String>emptyMap(), "operationName");
  assertNotNull("span is not null", span);
  List<MockSpan.LogEntry> logEntries = ((MockSpan) span).logEntries();
  assertEquals("span contains 1 log entry", 1, logEntries.size());
  assertEquals(
      "span log contains error field",
      GrpcFields.ERROR,
      logEntries.get(0).fields().get(Fields.EVENT));
  assertThat(
      "span log contains error.object field",
      logEntries.get(0).fields().get(Fields.ERROR_OBJECT),
      instanceOf(RuntimeException.class));
}
 
Example 4
Source File: TracingClientInterceptorTest.java    From java-grpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testTracedClientWithStreaming() {
  TracingClientInterceptor tracingInterceptor =
      TracingClientInterceptor.newBuilder().withTracer(clientTracer).withStreaming().build();
  TracedClient client = new TracedClient(grpcServer.getChannel(), tracingInterceptor);

  assertEquals("call should complete successfully", "Hello world", client.greet().getMessage());
  await().atMost(5, TimeUnit.SECONDS).until(reportedSpansSize(clientTracer), equalTo(1));
  assertEquals(
      "one span should have been created and finished for one client request",
      clientTracer.finishedSpans().size(),
      1);

  MockSpan span = clientTracer.finishedSpans().get(0);
  assertEquals("span should have prefix", span.operationName(), "helloworld.Greeter/SayHello");
  assertEquals("span should have no parents", span.parentId(), 0);
  List<String> events = new ArrayList<>(span.logEntries().size());
  for (MockSpan.LogEntry logEntry : span.logEntries()) {
    events.add((String) logEntry.fields().get(Fields.EVENT));
  }
  Assertions.assertThat(events)
      .as("span should contain streaming log fields")
      .contains(
          GrpcFields.CLIENT_CALL_SEND_MESSAGE,
          GrpcFields.CLIENT_CALL_HALF_CLOSE,
          GrpcFields.CLIENT_CALL_LISTENER_ON_MESSAGE);
  Assertions.assertThat(span.tags())
      .as("span should have base client tags")
      .isEqualTo(BASE_CLIENT_TAGS);
  assertFalse("span should have no baggage", span.context().baggageItems().iterator().hasNext());
}
 
Example 5
Source File: StandardSpanDecoratorTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void shouldTagException() {
    final ResponseEntity<String> response = client
            .getForEntity("http://localhost:8080/exception", String.class);

    assertThat(response.getStatusCode().series(), is(SERVER_ERROR));

    waitFor(Duration.ofSeconds(1));

    final MockSpan span = span();
    final Map<String, Object> tags = span.tags();

    assertThat(tags, hasEntry("http.path", "/exception"));
    assertThat(tags, hasEntry("error", true));

    final List<MockSpan.LogEntry> logs = span.logEntries();
    assertThat(logs, hasSize(3));

    assertThat(logs.get(0).fields(), hasEntry("message", "Error"));
    assertThat(logs.get(1).fields(),
            hasEntry("error.kind", "UnsupportedOperationException"));
    assertThat(logs.get(1).fields(), hasEntry(
            equalTo("error.object"),
            instanceOf(UnsupportedOperationException.class)));

    assertThat(logs.get(2).fields(),
            hasEntry(equalTo("stack"), instanceOf(String.class)));
}
 
Example 6
Source File: StandardSpanDecoratorTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void shouldTagException() {
    final ClientResponse response = client.get()
            .uri("/exception")
            .exchange()
            .block();

    assertTrue(response.statusCode().is5xxServerError());

    final MockSpan span = span();
    final Map<String, Object> tags = span.tags();

    assertThat(tags, hasEntry("http.path", "/exception"));
    assertThat(tags, hasEntry("error", true));

    final List<MockSpan.LogEntry> logs = span.logEntries();
    assertThat(logs, hasSize(3));

    assertThat(logs.get(0).fields(), hasEntry(equalTo("message"),
            hasFeature(Objects::toString, containsString("Error"))));
    assertThat(logs.get(1).fields(),
            hasEntry("error.kind", "UnsupportedOperationException"));
    assertThat(logs.get(1).fields().get("error.object"),
            instanceOf(UnsupportedOperationException.class));
    assertThat(logs.get(2).fields(),
            hasEntry(equalTo("stack"), instanceOf(String.class)));
}
 
Example 7
Source File: DataSourceTracerTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void shouldTraceErrors() {
    final DataSource dataSource = unit.trace(original);

    assertThrows(SQLException.class, () -> {
        try (final Connection connection = dataSource.getConnection();
             final Statement statement = connection.createStatement()) {

            statement.execute("SELECT * FROM MATRIX(4)");
        }
    });

    final List<MockSpan> spans = tracer.finishedSpans();
    final MockSpan span = getOnlyElement(spans);

    assertThat(span.operationName(), is("execute"));
    assertThat(span.tags(), hasEntry("component", "JDBC"));
    assertThat(span.tags(), hasEntry("db.statement", "SELECT * FROM MATRIX(4)"));
    assertThat(span.tags(), hasEntry("db.type", "sql"));
    assertThat(span.tags(), hasEntry("span.kind", "client"));
    assertThat(span.tags(), hasEntry("flow_id", "REcCvlqMSReeo7adheiYFA"));
    assertThat(span.tags(), hasEntry("error", true));

    final List<MockSpan.LogEntry> entries = span.logEntries();
    assertThat(entries, hasSize(3));

    assertThat(entries.get(0).fields().get("message").toString(),
            containsString("Function \"MATRIX\" not found"));

    assertThat(entries.get(1).fields(), hasEntry("error.kind", "JdbcSQLSyntaxErrorException"));
    assertThat(entries.get(1).fields(), hasEntry(equalTo("error.object"), instanceOf(SQLException.class)));

    assertThat(entries.get(2).fields().get("stack").toString(), containsString("at org.h2.jdbc"));
}
 
Example 8
Source File: ErrorReportingTest.java    From opentracing-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testErrorRecovery() {
    final int maxRetries = 1;
    int retries = 0;
    Object res = null;

    Span span = tracer.buildSpan("one").start();
    try (Scope scope = tracer.activateSpan(span)) {

        while (res == null && retries++ < maxRetries) {
            try {
                throw new RuntimeException("No url could be fetched");
            } catch (final Exception exc) {
                span.log(new TreeMap<String, Object>() {{
                    put(Fields.EVENT, Tags.ERROR);
                    put(Fields.ERROR_OBJECT, exc);
                }});
            }
        }
    }

    if (res == null) {
        Tags.ERROR.set(span, true); // Could not fetch anything.
    }
    span.finish();

    assertNull(tracer.scopeManager().activeSpan());

    List<MockSpan> spans = tracer.finishedSpans();
    assertEquals(spans.size(), 1);
    assertEquals(spans.get(0).tags().get(Tags.ERROR.getKey()), true);

    List<MockSpan.LogEntry> logs = spans.get(0).logEntries();
    assertEquals(logs.size(), maxRetries);
    assertEquals(logs.get(0).fields().get(Fields.EVENT), Tags.ERROR);
    assertNotNull(logs.get(0).fields().get(Fields.ERROR_OBJECT));
}
 
Example 9
Source File: BaseOpenTracingHookTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
protected final void assertSpanError(final Class<? extends Throwable> expectedException, final String expectedErrorMessage) {
    final MockSpan actual = getActualSpan();
    assertTrue((Boolean) actual.tags().get(Tags.ERROR.getKey()));
    List<MockSpan.LogEntry> actualLogEntries = actual.logEntries();
    assertThat(actualLogEntries.size(), is(1));
    assertThat(actualLogEntries.get(0).fields().size(), is(3));
    assertThat(actualLogEntries.get(0).fields().get(ShardingErrorLogTags.EVENT), is(ShardingErrorLogTags.EVENT_ERROR_TYPE));
    assertThat(actualLogEntries.get(0).fields().get(ShardingErrorLogTags.ERROR_KIND), is(expectedException.getName()));
    assertThat(actualLogEntries.get(0).fields().get(ShardingErrorLogTags.MESSAGE), is(expectedErrorMessage));
}
 
Example 10
Source File: AbstractBaseITests.java    From java-spring-web with Apache License 2.0 5 votes vote down vote up
public static void assertLogEvents(List<MockSpan.LogEntry> logs, List<String> events) {
    if (logs.size() != events.size()) {
        Assert.fail(String.format("Logs count does not match: expected %s, actual %s", events, logs));
    }

    for (int i = 0; i < logs.size(); i++) {
        Assert.assertEquals(events.get(i), logs.get(i).fields().get("event"));
    }
}
 
Example 11
Source File: TracingClientInterceptorTest.java    From java-grpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testTracedClientWithVerbosity() {
  TracingClientInterceptor tracingInterceptor =
      TracingClientInterceptor.newBuilder().withTracer(clientTracer).withVerbosity().build();
  TracedClient client = new TracedClient(grpcServer.getChannel(), tracingInterceptor);

  assertEquals("call should complete successfully", "Hello world", client.greet().getMessage());
  await().atMost(5, TimeUnit.SECONDS).until(reportedSpansSize(clientTracer), equalTo(1));
  assertEquals(
      "one span should have been created and finished for one client request",
      clientTracer.finishedSpans().size(),
      1);

  MockSpan span = clientTracer.finishedSpans().get(0);
  assertEquals("span should have prefix", span.operationName(), "helloworld.Greeter/SayHello");
  assertEquals("span should have no parents", span.parentId(), 0);
  System.out.println(span.logEntries());
  List<String> events = new ArrayList<>(span.logEntries().size());
  for (MockSpan.LogEntry logEntry : span.logEntries()) {
    events.add((String) logEntry.fields().get(Fields.EVENT));
  }
  Assertions.assertThat(events)
      .as("span should contain verbose log fields")
      .contains(
          GrpcFields.CLIENT_CALL_START,
          GrpcFields.CLIENT_CALL_SEND_MESSAGE,
          GrpcFields.CLIENT_CALL_HALF_CLOSE,
          GrpcFields.CLIENT_CALL_LISTENER_ON_HEADERS,
          GrpcFields.CLIENT_CALL_LISTENER_ON_MESSAGE,
          GrpcFields.CLIENT_CALL_LISTENER_ON_CLOSE);
  Assertions.assertThat(span.tags())
      .as("span should have base client tags")
      .isEqualTo(BASE_CLIENT_TAGS);
  assertFalse("span should have no baggage", span.context().baggageItems().iterator().hasNext());
}
 
Example 12
Source File: TracingServerInterceptorTest.java    From java-grpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testTracedServerWithStreaming() {
  TracingServerInterceptor tracingInterceptor =
      TracingServerInterceptor.newBuilder().withTracer(serverTracer).withStreaming().build();
  TracedService.addGeeterService(grpcServer.getServiceRegistry(), tracingInterceptor);

  assertEquals("call should complete successfully", "Hello world", client.greet().getMessage());
  await().atMost(5, TimeUnit.SECONDS).until(reportedSpansSize(serverTracer), equalTo(1));
  assertEquals(
      "one span should have been created and finished for one client request",
      serverTracer.finishedSpans().size(),
      1);

  MockSpan span = serverTracer.finishedSpans().get(0);
  assertEquals(
      "span should have default name", span.operationName(), "helloworld.Greeter/SayHello");
  assertEquals("span should have no parents", span.parentId(), 0);
  List<String> events = new ArrayList<>(span.logEntries().size());
  for (MockSpan.LogEntry logEntry : span.logEntries()) {
    events.add((String) logEntry.fields().get(Fields.EVENT));
  }
  Assertions.assertThat(events)
      .as("span should contain streaming log fields")
      .contains(
          GrpcFields.SERVER_CALL_LISTENER_ON_MESSAGE,
          GrpcFields.SERVER_CALL_LISTENER_ON_HALF_CLOSE,
          GrpcFields.SERVER_CALL_SEND_MESSAGE);
  Assertions.assertThat(span.tags())
      .as("span should have base server tags")
      .isEqualTo(BASE_SERVER_TAGS);
  assertFalse("span should have no baggage", span.context().baggageItems().iterator().hasNext());
}
 
Example 13
Source File: TracingServerInterceptorTest.java    From java-grpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testTracedServerWithVerbosity() {
  TracingServerInterceptor tracingInterceptor =
      TracingServerInterceptor.newBuilder().withTracer(serverTracer).withVerbosity().build();
  TracedService.addGeeterService(grpcServer.getServiceRegistry(), tracingInterceptor);

  assertEquals("call should complete successfully", "Hello world", client.greet().getMessage());
  await().atMost(5, TimeUnit.SECONDS).until(reportedSpansSize(serverTracer), equalTo(1));
  assertEquals(
      "one span should have been created and finished for one client request",
      serverTracer.finishedSpans().size(),
      1);

  MockSpan span = serverTracer.finishedSpans().get(0);
  assertEquals(
      "span should have default name", span.operationName(), "helloworld.Greeter/SayHello");
  assertEquals("span should have no parents", span.parentId(), 0);
  List<String> events = new ArrayList<>(span.logEntries().size());
  for (MockSpan.LogEntry logEntry : span.logEntries()) {
    events.add((String) logEntry.fields().get(Fields.EVENT));
  }
  Assertions.assertThat(events)
      .as("span should contain verbose log fields")
      .contains(
          GrpcFields.SERVER_CALL_LISTENER_ON_MESSAGE,
          GrpcFields.SERVER_CALL_LISTENER_ON_HALF_CLOSE,
          GrpcFields.SERVER_CALL_SEND_HEADERS,
          GrpcFields.SERVER_CALL_SEND_MESSAGE,
          GrpcFields.SERVER_CALL_CLOSE,
          GrpcFields.SERVER_CALL_LISTENER_ON_COMPLETE);
  Assertions.assertThat(span.tags())
      .as("span should have base server tags")
      .isEqualTo(BASE_SERVER_TAGS);
  assertFalse("span should have no baggage", span.context().baggageItems().iterator().hasNext());
}
 
Example 14
Source File: RewritableTracerTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private static void assertLog(final JsonObject expectedLog, final MockSpan.LogEntry logEntry, final String message) {
  final Map<String,?> fields = logEntry.fields();

  final String expectedEvent = expectedLog.getString("event");
  final JsonObject expectedFields = expectedLog.getObject("fields");

  final Number number = expectedLog.getNumber("timestampMicros");
  if (number != null)
    assertEquals(message, number.longValue(), logEntry.timestampMicros());
  else
    assertTrue(message, logEntry.timestampMicros() > 0);

  int given = 0;
  if (expectedEvent != null) {
    ++given;

    assertEquals(message, 1, fields.size());
    assertEquals(message, expectedEvent, fields.get("event"));
  }

  if (expectedFields != null) {
    ++given;
    assertEquals(message, expectedFields.size(), fields.size());
    for (final Map.Entry<String,Object> entry : expectedFields.entrySet()) {
      final String key = entry.getKey();
      assertEquals(message + " key " + key, entry.getValue(), fields.get(key));
    }
  }

  assertEquals(message, 1, given);
}
 
Example 15
Source File: RewritableTracerTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private static void assertLogs(final JsonObject expectedSpan, final MockSpan span, final String message) {
  final JsonArray expectedLogs = expectedSpan.getArray("logs");
  final List<MockSpan.LogEntry> logEntries = span.logEntries();
  if (expectedLogs == null) {
    assertEquals(message, 0, logEntries.size());
    return;
  }

  assertEquals(message, expectedLogs.size(), logEntries.size());
  for (int i = 0; i < expectedLogs.size(); ++i)
    assertLog(Objects.requireNonNull(expectedLogs.getObject(i)), logEntries.get(i), message + " log " + i);
}
 
Example 16
Source File: OpenTracingDecoratorTest.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
void assertErrorIsLogged(MockSpan span) {
    final MockSpan.LogEntry logEntry = span.logEntries().get(0);
    assertEquals("error", logEntry.fields().get("event"));

}
 
Example 17
Source File: OpenTracingDecoratorTest.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
void assertNoErrorLogged(MockSpan span) {
    for (final MockSpan.LogEntry logEntry : span.logEntries()) {
        assertNotEquals("error", logEntry.fields().get("event"));
    }
}
 
Example 18
Source File: LoggingTracer.java    From java-jaxrs with Apache License 2.0 votes vote down vote up
@JsonProperty("logs") abstract List<MockSpan.LogEntry> logEntries();