Application Insights integration with SpringBoot 2.7.12

207 Views Asked by At

I have a spring boot version, and applicationinsights-runtime-attach dependencies. Before main method, ApplicationInsights.attach() gets executed and the instrument key from json is getting picked but when it goes to run method of the main class, that is runApplication, it initialises the aiAppender class from spring-logback.xml, where in the instrument key comes as null.

My task is to publish the logs to application insights from springboot application and to create a dashboard using these appins (basically performance benchmarking). Specifically, time taken for a transaction. For that, I have annotated the methods with custom annotation @Timed

I have tried following steps:

Adding the Dependencies: {spring boot version - 2.7.12}

a. com.microsoft.azure:applicationsinsights-springboot-starter,2.6.4

b. com.microsoft.azure: applicationsinsights-logging-logback,2.6.4 dependency for ApplicationInsightsAppender

c. com.microsoft.azure: applicationsinsights-runtime-attach,3.4.14

d. com.microsoft.azure: applicationsinsights-core, 3.4.14

Connection string in yaml files as well as json

Applicationinsights.attach before runApplication method in main class

aiAppender in spring-logback.xml

@Timed custom annotation.

TimingAspect.java class having @Around(Timed package) { calculating execution time} This method also send the event using EventTelemetry i.e. TelemetryClient.trackEvent(event) where event is set with two properties; method name and execution time.

Annotated the methods with @Timed to capture their duration.

Kindly provide with the appropriate steps to send these logs to appins

1

There are 1 best solutions below

4
On

Configure the logback debug statements and print the status messages to the console during application startup.

spring-logback.xml:

<configuration>
    <statusListener class="ch.qos.logback.core.status.OnConsoleStatusListener" />

    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    
    <appender name="aiAppender" class="com.microsoft.applicationinsights.logback.ApplicationInsightsAppender">
        <instrumentationKey>${applicationinsights.instrumentationKey}</instrumentationKey>
    </appender>

    <logger name="com.example" level="INFO"/>
    <root level="INFO">
        <appender-ref ref="aiAppender"/>
    </root>
</configuration>
  • Below are the dependencies which I used in the application and also created a TimingAspect class to capture the method execution time.

build.gradle:

implementation 'com.microsoft.azure:applicationinsights-spring-boot-starter:2.6.4'
implementation 'com.microsoft.azure:applicationinsights-logging-logback:2.6.4'
implementation 'com.microsoft.azure:applicationinsights-runtime-attach:3.4.14'
implementation 'com.microsoft.azure:applicationinsights-core:3.4.14'

TimingAspect:

@Aspect
@Component
public class TimingAspect {

    @Around("@annotation(timed)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint, Timed timed) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;

        // Log or send telemetry with method name and execution time
        logMethodExecutionTime(joinPoint, timed.value(), executionTime);

        return result;
    }

    private void logMethodExecutionTime(ProceedingJoinPoint joinPoint, String customName, long executionTime) {
        // Use TelemetryClient to send telemetry data
        TelemetryClient telemetryClient = new TelemetryClient();
        EventTelemetry event = new EventTelemetry("MethodExecutionTime");
        event.getProperties().put("methodName", customName.isEmpty() ? joinPoint.getSignature().getName() : customName);
        event.getProperties().put("executionTime", String.valueOf(executionTime));
        telemetryClient.trackEvent(event);
    }
}

Main class:

@SpringBootApplication
public class sampletestapp {

    public static void main(String[] args) {
        // Attach Application Insights
        ApplicationInsights.attach();

        // Start OpenTelemetry
        startOpenTelemetry();

        // Run the Spring Boot application
        SpringApplication.run(YourApplication.class, args);
    }

    private static void startOpenTelemetry() {
        ApplicationInsightsSpanExporter applicationInsightsExporter = new ApplicationInsightsSpanExporter();

        // Optionally, add other exporters (e.g., LoggingSpanExporter) for debugging purposes
        LoggingSpanExporter loggingExporter = new LoggingSpanExporter();

        // Create an OpenTelemetry Tracer
        Tracer tracer = GlobalOpenTelemetry.getTracer("your-application-name");

        // Set up the span processors with the exporters
        OpenTelemetrySdk.getTracerProvider()
                .addSpanProcessor(SimpleSpanProcessor.create(applicationInsightsExporter))
                .addSpanProcessor(SimpleSpanProcessor.create(loggingExporter));

        // Optionally, you can also set other OpenTelemetry configurations

        // Register the ApplicationInsightsHttpFilter for automatic correlation of HTTP requests
        ApplicationInsightsHttpFilter instrumentedFilter = new ApplicationInsightsHttpFilter();
        // Optionally, configure the filter if needed
        // instrumentedFilter.set...

        // Register the filter with the servlet container
        GlobalOpenTelemetry.getPropagators().getHttpTextFormat().inject(tracer.getCurrentSpan().getContext(),
                instrumentedFilter, ApplicationInsightsHttpFilter.SETTER);

        // Optionally, you can register other instrumentation (e.g., JDBC, gRPC, etc.) based on your application needs
    }
}

enter image description here

App Insights:

enter image description here