mardi 23 février 2021

How to extract telemetry code from different methods? Decorator pattern? AOP?

We are using Application Insights to monitor different service calls in our applications. Data for Application Insights is provided by many different methods and classes but always in an identical way/by identical code fragments:

public class MyClassA {

  public void myMethodA() {
    final Instant startTime = Instant.now();

    try {
      callSomeServiceA();
    } catch (final Exception e) {
      sendExceptionDataToAppInsights(e);
      throw e;
    } finally {
      sendDataToAppInsights(MyClass.getName(), myMethodA.getName(), startTime, Instant.now());  
    }
  }

}

public class MyClassB {

  public String myMethodB() {
    final Instant startTime = Instant.now();

    try {
      return callSomeServiceB();
    } catch (final Exception e) {
      sendExceptionDataToAppInsights(e);
      throw e;
    } finally {
      sendDataToAppInsights(MyClass.getName(), myMethodA.getName(), startTime, Instant.now());  
    }
  }

}

How am I able to extract those wrapping try catch fragments to one point of responsibility? I took a look at the dacorator pattern but I guess it doesn't fit because of the different method signatures. Or does it?
Or is there a way to achieve it with AOP?

Aucun commentaire:

Enregistrer un commentaire