Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate Business logic and metrics log?

In lots of Applications, we need to log statistics metrics, such as hist, guage and so on. This will pollute the business logic. For example:

boolean buy(int id) {
  metrics.increament(); // for qps maybe.. 
  int remain = checkRemain();
  metrics.hist(remain); // log remain amount..
  if (remain > 0)
    return true;
  else
    return false;
}

which, I hope, I can only write down the biz logic, such as:

boolean buy(int id) {
  int remain = checkRemain();
  if (remain > 0)
    return true;
  else
    return false;
}

But also I can get the metrics.

My question is: what's the best practice to separate Business logic and metrics log?

I know Aspect--Oriented Programming may solve this, do I have any other choice?

like image 333
CodeBoy Avatar asked Apr 28 '19 08:04

CodeBoy


Video Answer


1 Answers

If you don't want to use AOP you can implement an observer

https://en.wikipedia.org/wiki/Observer_pattern

Define an Observer interface

public interface Observer {
    void buyed(int id, int remain);
}

Then use in business logic class:

 private List<Observer> observers = new ArrayList<>();
 public void addObserver(Observer observer) {
    this.observers.add(observer);
 }

 boolean buy(int id){    
    int remain = checkRemain();
    for (Observer observer : this.observers) {
        observer.buyed(id, remain);
    }
    if (remain > 0){  
      return true;
    } else
     return false;
}

Metrics class implements observer interface

class Metrics implements Observer {
   void buyed(int id, int remain){
       metrics.increment();
       metrics.hist(remain); 
   }
....
like image 117
Claudia Chersin Avatar answered Oct 22 '22 17:10

Claudia Chersin