Java Code Examples for io.opentracing.Span#log()

The following examples show how to use io.opentracing.Span#log() . 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: 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 2
Source File: HelloController.java    From Mastering-Distributed-Tracing with MIT License 6 votes vote down vote up
@GetMapping("/sayHello/{name}")
public String sayHello(@PathVariable String name, HttpServletRequest request) {
    Span span = startServerSpan("/sayHello", request);
    try (Scope scope = tracer.scopeManager().activate(span, false)) {
        Person person = getPerson(name);
        Map<String, String> fields = new LinkedHashMap<>();
        fields.put("name", person.getName());
        fields.put("title", person.getTitle());
        fields.put("description", person.getDescription());
        span.log(fields);

        String response = formatGreeting(person);
        span.setTag("response", response);

        return response;
    } finally {
        span.finish();
    }
}
 
Example 3
Source File: LoadWorker.java    From problematic-microservices with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Customer registerRandomCustomer(SpanContext parent) {
	String newCustomerJSon = getNewCustomerJSonString();
	RequestBody body = RequestBody.create(JSON, newCustomerJSon);
	Request request = new Request.Builder().url(urlCustomer + "/customers").put(body).build();

	SpanBuilder spanBuilder = getTracer().buildSpan("Create random user");
	spanBuilder.asChildOf(parent);
	Span span = spanBuilder.start();

	try (Scope scope = GlobalTracer.get().scopeManager().activate(span, false)) {
		Response response = httpClient.newCall(request).execute();
		if (!response.isSuccessful()) {
			Logger.log("Failed to create customer " + newCustomerJSon);
			return null;
		}
		return Customer.fromJSon(response.body().string());
	} catch (Throwable t) {
		span.log(OpenTracingUtil.getSpanLogMap(t));
	} finally {
		span.finish();
	}
	return null;
}
 
Example 4
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 5
Source File: SpanLogsAppender.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * This is called only for configured levels.
 * It will not be executed for DEBUG level if root logger is INFO.
 */
@Override
protected void append(ILoggingEvent event) {
  Span span = tracer.activeSpan();
  if (span != null) {
    Map<String, Object> logs = new HashMap<>(6);
    logs.put("logger", event.getLoggerName());
    logs.put("level", event.getLevel().toString());
    logs.put("thread", event.getThreadName());
    logs.put("message", event.getFormattedMessage());

    if (Level.ERROR.equals(event.getLevel())) {
      logs.put("event", Tags.ERROR);
    }

    IThrowableProxy throwableProxy = event.getThrowableProxy();
    if (throwableProxy instanceof ThrowableProxy) {
      Throwable throwable = ((ThrowableProxy)throwableProxy).getThrowable();
      // String stackTrace = ThrowableProxyUtil.asString(throwableProxy);
      if (throwable != null) {
        logs.put("error.object", throwable);
      }
    }
    span.log(TimeUnit.MICROSECONDS.convert(event.getTimeStamp(), TimeUnit.MILLISECONDS), logs);
  }
}
 
Example 6
Source File: WebSpanDecorator.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) {
    final Map<String, String> logs = new HashMap<>(2);
    logs.put("event", "reroute");
    logs.put(Tags.HTTP_URL.getKey(), request.absoluteURI());
    logs.put(Tags.HTTP_METHOD.getKey(), request.method().toString());
    span.log(logs);
}
 
Example 7
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 8
Source File: ErrorMessageSpanDecorator.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.MESSAGE, error.getMessage()));
}
 
Example 9
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 10
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 11
Source File: StandardTagsServletFilterSpanDecorator.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Override
public void onTimeout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                      long timeout, Span span) {
  Map<String, Object> timeoutLogs = new HashMap<>(2);
  timeoutLogs.put("event", "timeout");
  timeoutLogs.put("timeout", timeout);
  span.log(timeoutLogs);
}
 
Example 12
Source File: HandlerInterceptorSpanDecorator.java    From java-spring-web with Apache License 2.0 5 votes vote down vote up
@Override
public void onAfterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                              Object handler, Exception ex, Span span) {
    Map<String, Object> logs = new HashMap<>(2);
    logs.put("event", "afterCompletion");
    logs.put(HandlerUtils.HANDLER, handler);
    span.log(logs);
}
 
Example 13
Source File: Hello.java    From opentracing-tutorial with Apache License 2.0 5 votes vote down vote up
private String formatString(String helloTo) {
    Span span = tracer.buildSpan("formatString").start();
    try (Scope scope = tracer.scopeManager().activate(span)) {
        String helloStr = getHttp(8081, "format", "helloTo", helloTo);
        span.log(ImmutableMap.of("event", "string-format", "value", helloStr));
        return helloStr;
    } finally {
        span.finish();
    }
}
 
Example 14
Source File: QuarkusSmallRyeTracingStandaloneVertxDynamicFeature.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void addExceptionLogs(Span span, Throwable throwable) {
    Tags.ERROR.set(span, true);
    if (throwable != null) {
        Map<String, Object> errorLogs = new HashMap<>(2);
        errorLogs.put("event", Tags.ERROR.getKey());
        errorLogs.put("error.object", throwable);
        span.log(errorLogs);
    }
}
 
Example 15
Source File: SpanFinishingFilter.java    From java-jaxrs with Apache License 2.0 5 votes vote down vote up
private static void addExceptionLogs(Span span, Throwable throwable) {
  Tags.ERROR.set(span, true);
  if (throwable != null) {
    Map<String, Object> errorLogs = new HashMap<>(2);
    errorLogs.put("event", Tags.ERROR.getKey());
    errorLogs.put("error.object", throwable);
    span.log(errorLogs);
  }
}
 
Example 16
Source File: TracingServerInterceptor.java    From java-grpc with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
Span getSpanFromHeaders(Map<String, String> headers, String operationName) {
  Map<String, Object> fields = null;
  Tracer.SpanBuilder spanBuilder = tracer.buildSpan(operationName);
  try {
    SpanContext parentSpanCtx =
        tracer.extract(Format.Builtin.HTTP_HEADERS, new TextMapAdapter(headers));
    if (parentSpanCtx != null) {
      spanBuilder = spanBuilder.asChildOf(parentSpanCtx);
    }
  } catch (IllegalArgumentException iae) {
    spanBuilder = spanBuilder.withTag(Tags.ERROR, Boolean.TRUE);
    fields =
        ImmutableMap.<String, Object>builder()
            .put(Fields.EVENT, GrpcFields.ERROR)
            .put(
                Fields.ERROR_OBJECT,
                new RuntimeException("Parent span context extract failed", iae))
            .build();
  }
  Span span =
      spanBuilder
          .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
          .withTag(Tags.COMPONENT.getKey(), GrpcTags.COMPONENT_NAME)
          .start();
  if (fields != null) {
    span.log(fields);
  }
  return span;
}
 
Example 17
Source File: RestTemplateSpanDecorator.java    From java-spring-web with Apache License 2.0 4 votes vote down vote up
@Override
public void onError(HttpRequest httpRequest, Throwable ex, Span span) {
    Tags.ERROR.set(span, Boolean.TRUE);
    span.log(errorLogs(ex));
}
 
Example 18
Source File: WebClientSpanDecorator.java    From java-spring-web with Apache License 2.0 4 votes vote down vote up
@Override
public void onError(final ClientRequest clientRequest, final Throwable throwable, final Span span) {
    Tags.ERROR.set(span, Boolean.TRUE);
    span.log(errorLogs(throwable));
}
 
Example 19
Source File: OpenTracingFilter.java    From flower with Apache License 2.0 4 votes vote down vote up
@Override
public Object doFilter(Object message, ServiceContext context, FilterChain chain) {
  String spanName = context.getFlowName() + "." + context.getCurrentServiceName();
  SpanBuilder spanBuilder = getTracer().buildSpan(spanName);
  SpanContext spanContext = null;
  Map<String, String> headerMap = getMap(context);
  if (headerMap != null) {
    spanContext = getTracer().extract(Format.Builtin.TEXT_MAP, new TextMapAdapter(headerMap));
    if (spanContext != null) {
      spanBuilder.asChildOf(spanContext);
    }
  }


  Span span = spanBuilder.start();
  span.log("Flower Trace start.");

  span.setTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER);
  Scope scope = tracer.scopeManager().activate(span);
  addAttachements(context, span);

  span.setTag("id", context.getId());
  span.setTag("sync", context.isSync());
  span.setTag("codec", context.getCodec());
  span.setTag("flowName", context.getFlowName());
  span.setTag("serviceName", context.getCurrentServiceName());
  span.setTag("flowMessage.transactionId", context.getFlowMessage().getTransactionId());
  span.setTag("flowMessage.messageType", context.getFlowMessage().getMessageType());

  try {
    return chain.doFilter(message, context);
  } catch (Exception ex) {
    Tags.ERROR.set(span, true);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put(Fields.EVENT, "error");
    map.put(Fields.ERROR_OBJECT, ex);
    map.put(Fields.MESSAGE, ex.getMessage());
    span.log(map);
    throw new FlowException(ex);
  } finally {
    span.log("Flower Trace end.");
    scope.close();
    span.finish();
  }

}
 
Example 20
Source File: AbstractLogger.java    From microprofile-sandbox with Apache License 2.0 2 votes vote down vote up
/**
 * Write the {@link LogEvent} to Span Logging.
 * 
 * <p>
 * Note: This method expects Tracing to be available. As such, a call
 * to this method must be wrapped in {@link #isSpanLoggable(org.eclipse.microprofile.logging.Level)}
 * </p>
 * 
 * @param event The log data.
 */
private void writeSpan(T event) {
  final Map<String, ?> fields = build(event);
  final Span span = tracer.activeSpan();
  span.log(fields);
}