@PrasunkumarBheemireddy-2372- Thanks for your questions I have answered them inline below.
Which starter lib/pack need to be added in the pom.xml file?
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>applicationinsights-spring-boot-starter</artifactId>
<version>2.5.1</version>
</dependency>
You could refer to this page for list of versions of applicationinsights-spring-boot-starter
.
Where the instrumentation key/ConnectionString needs to be added ?
You will have to add the below line to the Application.properties files which is present under the Resources folder.
]3
azure.application-insights.instrumentation-key=<YOUR KEY>
How to use the telemetry client in the code
The below snippet is a sample code where. The REST API /GREETINGS
returns "Hello World" and /USERS
returns users from the backend.
The snippet has been referenced from the Deep Application Monitoring post.
The below snippet makes use of the Telemetry client to track success requests and errors (Exceptions)
@RestController
@RequestMapping("/")
public class Controller {
@Autowired
UserRepo userRepo;
@Autowired
TelemetryClient telemetryClient;
@GetMapping("/greetings")
public String greetings() {
// send event
telemetryClient.trackEvent("URI /greeting is triggered");
return "Hello World!";
}
@GetMapping("/users")
public List<User> users() {
try {
List<User> users;
// measure DB query benchmark
long startTime = System.nanoTime();
users = userRepo.findAll();
long endTime = System.nanoTime();
MetricTelemetry benchmark = new MetricTelemetry();
benchmark.setName("DB query");
benchmark.setValue(endTime - startTime);
telemetryClient.trackMetric(benchmark);
return users;
} catch (Exception e) {
// send exception information
telemetryClient.trackEvent("Error");
telemetryClient.trackTrace("Exception: " + e.getMessage());
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
}