io.opentracing.log.Fields Java Examples

The following examples show how to use io.opentracing.log.Fields. 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: PrometheusBasedResourceLimitChecks.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<Long> executeQuery(final String query, final Span span) {

        final Promise<Long> result = Promise.promise();
        LOG.trace("running Prometheus query [URL: {}, query: {}]", url, query);
        newQueryRequest(query).send(sendAttempt -> {
            if (sendAttempt.succeeded()) {
                final HttpResponse<JsonObject> response = sendAttempt.result();
                result.complete(extractLongValue(response.body(), span));
            } else {
                final Map<String, Object> items = Map.of(
                        Fields.EVENT, Tags.ERROR.getKey(),
                        Fields.MESSAGE, "failed to run Prometheus query",
                        "URL", url,
                        "query", query,
                        Fields.ERROR_KIND, "Exception",
                        Fields.ERROR_OBJECT, sendAttempt.cause());
                TracingHelper.logError(span, items);
                LOG.warn("failed to run Prometheus query [URL: {}, query: {}]: {}",
                        url, query, sendAttempt.cause().getMessage());
                result.fail(sendAttempt.cause());
            }
        });
        return result.future();
    }
 
Example #2
Source File: TracingHelperTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a logging an error with given exception creates the appropriate log items.
 */
@SuppressWarnings("unchecked")
@Test
public void testLogErrorWithException() {
    final Span span = mock(Span.class);
    final Exception exception = new Exception("my error message");

    TracingHelper.logError(span, exception);
    final ArgumentCaptor<Map<String, ?>> itemsCaptor = ArgumentCaptor.forClass(Map.class);
    verify(span).log(itemsCaptor.capture());

    final Map<?, ?> capturedItemsMap = itemsCaptor.getValue();
    assertThat(capturedItemsMap).isNotNull();
    assertThat(capturedItemsMap).hasSize(2);
    assertThat(capturedItemsMap.get(Fields.ERROR_OBJECT)).isEqualTo(exception);
    assertThat(capturedItemsMap.get(Fields.EVENT)).isEqualTo(Tags.ERROR.getKey());
}
 
Example #3
Source File: TracingHelperTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a logging an error with a single item creates the appropriate log items.
 */
@SuppressWarnings("unchecked")
@Test
public void testLogErrorWithSingletonMap() {
    final Span span = mock(Span.class);
    final String errorMessage = "my error message";

    TracingHelper.logError(span, Collections.singletonMap(Fields.MESSAGE, errorMessage));
    final ArgumentCaptor<Map<String, ?>> itemsCaptor = ArgumentCaptor.forClass(Map.class);
    verify(span).log(itemsCaptor.capture());

    final Map<?, ?> capturedItemsMap = itemsCaptor.getValue();
    assertThat(capturedItemsMap).isNotNull();
    assertThat(capturedItemsMap).hasSize(2);
    assertThat(capturedItemsMap.get(Fields.MESSAGE)).isEqualTo(errorMessage);
    assertThat(capturedItemsMap.get(Fields.EVENT)).isEqualTo(Tags.ERROR.getKey());
}
 
Example #4
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 #5
Source File: AmqpAdapterClientCommandConsumer.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private static void traceCommand(final HonoConnection con, final ResourceIdentifier address,
        final Message message) {
    final Tracer tracer = con.getTracer();
    if (tracer instanceof NoopTracer) {
        return;
    }

    // try to extract Span context from incoming message
    final SpanContext spanContext = TracingHelper.extractSpanContext(tracer, message);
    final Span currentSpan = createSpan("receive command", address.getTenantId(),
            address.getResourceId(), null, tracer, spanContext);
    final Object correlationId = message.getCorrelationId();
    if (correlationId == null || correlationId instanceof String) {
        final Map<String, String> items = new HashMap<>(5);
        items.put(Fields.EVENT, "received command message");
        TracingHelper.TAG_CORRELATION_ID.set(currentSpan, ((String) correlationId));
        items.put("to", message.getAddress());
        items.put("reply-to", message.getReplyTo());
        items.put("name", message.getSubject());
        items.put("content-type", message.getContentType());
        currentSpan.log(items);
    } else {
        TracingHelper.logError(currentSpan,
                "received invalid command message. correlation-id is not of type string.");
    }
}
 
Example #6
Source File: TracingHelperTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a logging an error creates the appropriate log items.
 */
@SuppressWarnings("unchecked")
@Test
public void testLogErrorWithMessage() {
    final Span span = mock(Span.class);
    final String errorMessage = "my error message";

    TracingHelper.logError(span, errorMessage);
    final ArgumentCaptor<Map<String, ?>> itemsCaptor = ArgumentCaptor.forClass(Map.class);
    verify(span).log(itemsCaptor.capture());

    final Map<?, ?> capturedItemsMap = itemsCaptor.getValue();
    assertThat(capturedItemsMap).isNotNull();
    assertThat(capturedItemsMap).hasSize(2);
    assertThat(capturedItemsMap.get(Fields.MESSAGE)).isEqualTo(errorMessage);
    assertThat(capturedItemsMap.get(Fields.EVENT)).isEqualTo(Tags.ERROR.getKey());
}
 
Example #7
Source File: GrpcFields.java    From java-grpc with Apache License 2.0 6 votes vote down vote up
private static void logCallError(Span span, String message, Throwable cause, String name) {
  ImmutableMap.Builder<String, Object> builder =
      ImmutableMap.<String, Object>builder().put(Fields.EVENT, GrpcFields.ERROR);
  String causeMessage = null;
  if (cause != null) {
    builder.put(Fields.ERROR_OBJECT, cause);
    causeMessage = cause.getMessage();
  }
  if (message != null) {
    builder.put(Fields.MESSAGE, message);
  } else if (causeMessage != null) {
    builder.put(Fields.MESSAGE, causeMessage);
  } else {
    builder.put(Fields.MESSAGE, name + " call failed");
  }
  span.log(builder.build());
}
 
Example #8
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Marks an <em>OpenTracing</em> span as erroneous and logs several items.
 * <p>
 * This method does <em>not</em> finish the span.
 *
 * @param span The span to mark.
 * @param items The items to log on the span. Note that this method will
 *               also log an item using {@code event} as key and {@code error}
 *               as the value if the items do not contain such an entry already.
 *               A given {@code event} item with a different value will be ignored.
 */
public static void logError(final Span span, final Map<String, ?> items) {
    if (span != null) {
        Tags.ERROR.set(span, Boolean.TRUE);
        if (items != null && !items.isEmpty()) {
            // ensure 'event' item is set and has value 'error'
            final Object event = items.get(Fields.EVENT);
            if (event == null || !Tags.ERROR.getKey().equals(event)) {
                final HashMap<String, Object> itemsWithErrorEvent = new HashMap<>(items.size() + 1);
                itemsWithErrorEvent.putAll(items);
                itemsWithErrorEvent.put(Fields.EVENT, Tags.ERROR.getKey());
                span.log(itemsWithErrorEvent);
            } else {
                span.log(items);
            }
        } else {
            span.log(Tags.ERROR.getKey());
        }
    }
}
 
Example #9
Source File: ErrorSpanDecorator.java    From opentracing-toolbox with MIT License 6 votes vote down vote up
@Override
public void onError(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final Object handler,
        final Exception error,
        final Span span) {

    span.setTag(Tags.ERROR, true);

    final Map<String, Object> fields = new HashMap<>(2);
    fields.put(Fields.ERROR_KIND, error.getClass().getSimpleName());
    fields.put(Fields.ERROR_OBJECT, error);

    span.log(fields);
}
 
Example #10
Source File: OpenTracingBridgeTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testErrorLogging() {
    Span span = apmTracer.buildSpan("someWork").start();
    try (Scope scope = apmTracer.activateSpan(span)) {
        throw new RuntimeException("Catch me if you can");
    } catch (Exception ex) {
        Tags.ERROR.set(span, true);
        span.log(Map.of(Fields.EVENT, "error", Fields.ERROR_OBJECT, ex, Fields.MESSAGE, ex.getMessage()));
    } finally {
        span.finish();
    }
    assertThat(reporter.getTransactions()).hasSize(1);
    assertThat(reporter.getFirstTransaction().getResult()).isEqualTo("error");
    assertThat(reporter.getErrors()).hasSize(1);
    assertThat(reporter.getFirstError().getException()).isNotNull();
    assertThat(reporter.getFirstError().getException().getMessage()).isEqualTo("Catch me if you can");
    assertThat(reporter.getFirstError().getTraceContext().getParentId()).isEqualTo(reporter.getFirstTransaction().getTraceContext().getId());
}
 
Example #11
Source File: PrometheusBasedResourceLimitChecksTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the connection duration limit check returns {@code false} if no metrics are
 * available (yet).
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testConnectionDurationLimitNotExceededForMissingMetrics(final VertxTestContext ctx) {

    givenDeviceConnectionDurationInMinutes(null);
    final TenantObject tenant = TenantObject.from("tenant", true)
            .setResourceLimits(new ResourceLimits()
                    .setConnectionDuration(new ConnectionDuration()
                            .setMaxDuration(100L)
                            .setEffectiveSince(Instant.parse("2019-01-03T14:30:00Z"))
                            .setPeriod(new ResourceLimitsPeriod()
                                    .setMode("days")
                                    .setNoOfDays(30))));
    limitChecksImpl.isConnectionDurationLimitReached(tenant, mock(SpanContext.class))
            .onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    // THEN the limit is not exceeded
                    assertFalse(response);
                    verify(request).send(any(Handler.class));
                    // AND the span is not marked as erroneous
                    verify(span).log(argThat((Map<String, ?> map) -> !"error".equals(map.get(Fields.EVENT))));
                });
                ctx.completeNow();
            }));
}
 
Example #12
Source File: OpenTracingBridgeTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
@Test
void testErrorLoggingWithoutScope() {
    Span span = apmTracer.buildSpan("someWork").start();
    try {
        throw new RuntimeException("Catch me if you can");
    } catch (Exception ex) {
        Tags.ERROR.set(span, true);
        span.log(Map.of(Fields.EVENT, "error", Fields.ERROR_OBJECT, ex, Fields.MESSAGE, ex.getMessage()));
    } finally {
        span.finish();
    }
    assertThat(reporter.getTransactions()).hasSize(1);
    assertThat(reporter.getErrors()).hasSize(1);
    assertThat(reporter.getFirstError().getException()).isNotNull();
    assertThat(reporter.getFirstError().getException().getMessage()).isEqualTo("Catch me if you can");
    assertThat(reporter.getFirstError().getTraceContext().getParentId()).isEqualTo(reporter.getFirstTransaction().getTraceContext().getId());
}
 
Example #13
Source File: ErrorStackSpanDecorator.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Override
public void onError(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final Object handler,
        final Exception error,
        final Span span) {

    span.log(singletonMap(Fields.STACK, toString(error)));
}
 
Example #14
Source File: ErrorStackSpanDecorator.java    From riptide with MIT License 5 votes vote down vote up
@Override
public void onError(final Span span, final RequestArguments arguments, final Throwable error) {
    final String stack = arguments.getAttribute(STACK)
            .map(original -> renderer.render(error, original.get()))
            .orElseGet(() -> renderer.render(error));

    span.log(singletonMap(Fields.STACK, stack));
}
 
Example #15
Source File: ErrorStackSpanDecorator.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Override
public void onError(
        final ServerWebExchange exchange,
        final Throwable error,
        final Span span) {

    span.log(singletonMap(Fields.STACK, toString(error)));
}
 
Example #16
Source File: AbstractCouchbaseRequest.java    From couchbase-jvm-core with Apache License 2.0 5 votes vote down vote up
@Override
public void fail(final Throwable throwable) {
    observable.onError(throwable);
    if (span != null) {
        Map<String, Object> exData = new HashMap<String, Object>();
        exData.put(Fields.ERROR_KIND, "Exception");
        exData.put(Fields.ERROR_OBJECT, throwable);
        exData.put(Fields.EVENT, "failed");
        exData.put(Fields.MESSAGE, throwable.getMessage());
        span.log(exData);
    }
}
 
Example #17
Source File: ErrorSpanDecorator.java    From riptide with MIT License 5 votes vote down vote up
@Override
public void onError(final Span span, final RequestArguments arguments, final Throwable error) {
    span.setTag(Tags.ERROR, true);
    span.log(ImmutableMap.of(
            Fields.ERROR_KIND, error.getClass().getSimpleName(),
            Fields.ERROR_OBJECT, error
    ));
}
 
Example #18
Source File: ErrorMessageSpanDecorator.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Override
public void onError(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final Object handler,
        final Exception error,
        final Span span) {

    span.log(singletonMap(Fields.MESSAGE, error.getMessage()));
}
 
Example #19
Source File: ErrorSpanDecorator.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Override
public void onError(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final Throwable error,
        final Span span) {

    span.setTag(Tags.ERROR, true);

    final Map<String, Object> fields = new HashMap<>();
    fields.put(Fields.ERROR_KIND, error.getClass().getSimpleName());
    fields.put(Fields.ERROR_OBJECT, error);

    span.log(fields);
}
 
Example #20
Source File: ErrorMessageSpanDecorator.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Override
public void onError(
        final HttpServletRequest request,
        final HttpServletResponse response,
        final Throwable error,
        final Span span) {

    span.log(singletonMap(Fields.MESSAGE, error.getMessage()));
}
 
Example #21
Source File: OpenTracingTracer.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public void completeSend(TraceableMessage message, String outcome) {
    Object cachedSpan = message.getTracingContext(SEND_SPAN_CONTEXT_KEY);
    if (cachedSpan != null) {
        Span span = (Span) cachedSpan;

        Map<String, String> fields = new HashMap<>();
        fields.put(Fields.EVENT, DELIVERY_SETTLED);
        fields.put(STATE, outcome == null ? "null" : outcome);

        span.log(fields);

        span.finish();
    }
}
 
Example #22
Source File: OpenTracingTracer.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void addDeliveryLogIfNeeded(DeliveryOutcome outcome, Span span) {
    Map<String, Object> fields = null;
    if (outcome == DeliveryOutcome.EXPIRED) {
        fields = new HashMap<>();
        fields.put(Fields.EVENT, MESSAGE_EXPIRED);
    } else if (outcome == DeliveryOutcome.REDELIVERIES_EXCEEDED) {
        fields = new HashMap<>();
        fields.put(Fields.EVENT, REDELIVERIES_EXCEEDED);
    }

    if (fields != null) {
        span.log(fields);
    }
}
 
Example #23
Source File: OpenTracingTracer.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
public void asyncDeliveryComplete(TraceableMessage message, DeliveryOutcome outcome, Throwable throwable) {
    Scope scope = (Scope) message.removeTracingContext(ONMESSAGE_SCOPE_CONTEXT_KEY);
    try {
        if (scope != null) {
            scope.close();
        }
    } finally {
        Span span = (Span) message.getTracingContext(DELIVERY_SPAN_CONTEXT_KEY);
        if (span != null) {
            try {
                if (throwable != null) {
                    span.setTag(Tags.ERROR, true);

                    Map<String, Object> fields = new HashMap<>();
                    fields.put(Fields.EVENT, ERROR_EVENT);
                    fields.put(Fields.ERROR_OBJECT, throwable);
                    fields.put(Fields.MESSAGE, "Application error, exception thrown from onMessage.");

                    span.log(fields);
                } else {
                    addDeliveryLogIfNeeded(outcome, span);
                }
            } finally {
                span.finish();
            }
        }
    }
}
 
Example #24
Source File: SQL.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private static <T> T traceSuccess(final T result, final Span span, final BiConsumer<T, Map<String, Object>> extractor) {
    final Map<String, Object> log = new HashMap<>();
    log.put(Fields.EVENT, "success");
    if (extractor != null) {
        extractor.accept(result, log);
    }
    span.log(log);
    span.finish();
    return result;
}
 
Example #25
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 #26
Source File: ComponentMetaDataDecorator.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void onReroute(final HttpServerRequest request, final Span span) {
    LOG.trace("logging re-routed request [method: {}, URI: {}]", request.method(), request.absoluteURI());
    final Map<String, String> logs = new HashMap<>(3);
    logs.put(Fields.EVENT, "reroute");
    logs.put(Tags.HTTP_URL.getKey(), request.absoluteURI());
    logs.put(Tags.HTTP_METHOD.getKey(), request.method().toString());
    span.log(logs);
}
 
Example #27
Source File: PrometheusBasedResourceLimitChecksTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the message limit check returns {@code false} if no metrics are
 * available (yet).
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testMessageLimitNotExceededForMissingMetrics(final VertxTestContext ctx) {

    givenDataVolumeUsageInBytes(null);
    final long incomingMessageSize = 20;
    final TenantObject tenant = TenantObject.from("tenant", true)
            .setResourceLimits(new ResourceLimits()
                    .setDataVolume(new DataVolume()
                            .setMaxBytes(100L)
                            .setEffectiveSince(Instant.parse("2019-01-03T14:30:00Z"))
                            .setPeriod(new ResourceLimitsPeriod()
                                    .setMode("days")
                                    .setNoOfDays(30))));

    limitChecksImpl.isMessageLimitReached(tenant, incomingMessageSize, spanContext)
            .onComplete(ctx.succeeding(response -> {
                ctx.verify(() -> {
                    // THEN the limit is not exceeded
                    assertFalse(response);
                    verify(request).send(any(Handler.class));
                    // AND the span is not marked as erroneous
                    verify(span).log(argThat((Map<String, ?> map) -> !"error".equals(map.get(Fields.EVENT))));
                });
                ctx.completeNow();
            }));
}
 
Example #28
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a set of items to log for an error.
 *
 * @param error The error.
 * @return The items to log.
 */
public static Map<String, Object> getErrorLogItems(final Throwable error) {
    final Map<String, Object> items = new HashMap<>(2);
    items.put(Fields.EVENT, Tags.ERROR.getKey());
    if (error != null) {
        items.put(Fields.ERROR_OBJECT, error);
    }
    return items;
}
 
Example #29
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Marks an <em>OpenTracing</em> span as erroneous and logs a message.
 * <p>
 * This method does <em>not</em> finish the span.
 *
 * @param span The span to mark.
 * @param message The message to log on the span.
 * @throws NullPointerException if message is {@code null}.
 */
public static void logError(final Span span, final String message) {
    if (span != null) {
        Objects.requireNonNull(message);
        final Map<String, String> items = new HashMap<>(2);
        items.put(Fields.MESSAGE, message);
        items.put(Fields.EVENT, Tags.ERROR.getKey());
        logError(span, items);
    }
}
 
Example #30
Source File: TracingHelper.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Marks an <em>OpenTracing</em> span as erroneous, logs a message and an error.
 * <p>
 * This method does <em>not</em> finish the span.
 *
 * @param span The span to mark.
 * @param message The message to log on the span.
 * @param error The error to log on the span.
 * @throws NullPointerException if message and error are {@code null}.
 */
public static void logError(final Span span, final String message, final Throwable error) {
    if (span != null) {
        if (message == null && error == null) {
            throw new NullPointerException("Either message or error must not be null");
        }
        final Map<String, Object> items = new HashMap<>(3);
        items.put(Fields.EVENT, Tags.ERROR.getKey());
        Optional.ofNullable(message)
                .ifPresent(ok -> items.put(Fields.MESSAGE, message));
        Optional.ofNullable(error)
                .ifPresent(ok -> items.put(Fields.ERROR_OBJECT, error));
        logError(span, items);
    }
}