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?
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);
}
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With