Skip to content

Commit

Permalink
added metrics part
Browse files Browse the repository at this point in the history
  • Loading branch information
maeddes committed Jul 25, 2024
1 parent 6856938 commit 4dc9bb3
Show file tree
Hide file tree
Showing 4 changed files with 427 additions and 99 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.novatec.todobackend;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
Expand All @@ -10,45 +11,57 @@
//Basic Otel API & SDK
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.semconv.ResourceAttributes;

//Tracing and Spans
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;

import io.opentelemetry.exporter.logging.LoggingMetricExporter;
import io.opentelemetry.exporter.logging.LoggingSpanExporter;
import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter;

import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
import io.opentelemetry.context.propagation.ContextPropagators;


@SuppressWarnings("deprecation")
@Configuration
public class OpenTelemetryConfiguration {

@Bean
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public OpenTelemetry openTelemetry(){
public OpenTelemetry openTelemetry() {

Resource resource = Resource.getDefault().toBuilder().put(ResourceAttributes.SERVICE_NAME, "todobackend").put(ResourceAttributes.SERVICE_VERSION, "0.1.0").build();
Resource resource = Resource.getDefault().toBuilder().put(ResourceAttributes.SERVICE_NAME, "todobackend")
.put(ResourceAttributes.SERVICE_VERSION, "0.1.0").build();

OtlpGrpcSpanExporter jaegerOtlpExporter =
OtlpGrpcSpanExporter.builder()
.setEndpoint("http://localhost:4317")
.build();
OtlpGrpcSpanExporter jaegerOtlpExporter = OtlpGrpcSpanExporter.builder()
.setEndpoint("http://localhost:4317")
.build();

SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder()
.addSpanProcessor(SimpleSpanProcessor.create(LoggingSpanExporter.create()))
.addSpanProcessor(SimpleSpanProcessor.create(jaegerOtlpExporter))
.setResource(resource)
.build();
.addSpanProcessor(SimpleSpanProcessor.create(LoggingSpanExporter.create()))
.addSpanProcessor(SimpleSpanProcessor.create(jaegerOtlpExporter))
.setResource(resource)
.build();

SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder()
.registerMetricReader(
PeriodicMetricReader
.builder(LoggingMetricExporter.create())
.setInterval(Duration.ofSeconds(10))
.build())
.setResource(resource)
.build();


OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
.setTracerProvider(sdkTracerProvider)
.setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
.build();
.setTracerProvider(sdkTracerProvider)
.setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
.setMeterProvider(sdkMeterProvider)
.build();

return openTelemetry;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@
import org.springframework.web.bind.annotation.RestController;

import io.opentelemetry.api.OpenTelemetry;

import static io.opentelemetry.api.common.AttributeKey.stringKey;

import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Scope;
import io.opentelemetry.api.trace.Span;
Expand All @@ -38,6 +45,8 @@ public class TodobackendApplication {

private OpenTelemetry openTelemetry;
private Tracer tracer;
private Meter meter;
private LongCounter counter;

@Value("${HOSTNAME:not_set}")
String hostname;
Expand All @@ -51,7 +60,13 @@ public class TodobackendApplication {
public TodobackendApplication(OpenTelemetry openTelemetry) {
this.openTelemetry = openTelemetry;
tracer = openTelemetry.getTracer(TodobackendApplication.class.getName(), "0.1.0");

meter = openTelemetry.getMeter(TodobackendApplication.class.getName());

counter = meter.counterBuilder("todobackend.requests.counter")
.setDescription("How many times the GET call has been invoked.")
.setUnit("requests")
.build();

}

private String getInstanceId() {
Expand Down Expand Up @@ -83,22 +98,23 @@ List<String> getTodos() {

todoRepository.findAll().forEach(todo -> todos.add(todo.getTodo()));
logger.info("GET /todos/ " + todos.toString());
counter.add(1,Attributes.of(stringKey("http.method"), "GET"));

return todos;
}

@PostMapping("/todos/{todo}")
String addTodo(HttpServletRequest request, HttpServletResponse response, @PathVariable String todo){
String addTodo(HttpServletRequest request, HttpServletResponse response, @PathVariable String todo) {

logger.info("POST /todos/ "+todo.toString());
logger.info("POST /todos/ " + todo.toString());

Span span = tracer.spanBuilder("addTodo").setSpanKind(SpanKind.SERVER).startSpan();

span.setAttribute("http.method", request.getMethod());
span.setAttribute("http.url", request.getRequestURL().toString());
span.setAttribute("client.address", request.getRemoteAddr());
span.setAttribute("user.agent",request.getHeader("User-Agent"));
span.setAttribute("user.agent", request.getHeader("User-Agent"));

try (Scope scope = span.makeCurrent()) {
this.someInternalMethod(todo);
response.setStatus(HttpServletResponse.SC_CREATED);
Expand All @@ -111,33 +127,33 @@ String addTodo(HttpServletRequest request, HttpServletResponse response, @PathVa
} finally {
span.end();
}
logger.info("Span.toString():"+span.toString());

logger.info("Span.toString():" + span.toString());
return todo;

}
}

String someInternalMethod(String todo){
String someInternalMethod(String todo) {

Span childSpan = tracer.spanBuilder("someInternalMethod").setSpanKind(SpanKind.INTERNAL).startSpan();

todoRepository.save(new Todo(todo));
if(todo.equals("slow")){

if (todo.equals("slow")) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(todo.equals("fail")){
}
if (todo.equals("fail")) {

System.out.println("Failing ...");
throw new RuntimeException();

}

logger.info("childSpan.toString():"+childSpan.toString());
}

logger.info("childSpan.toString():" + childSpan.toString());
childSpan.end();
return todo;

Expand Down
Loading

0 comments on commit 4dc9bb3

Please sign in to comment.