Ponnapati Lourdu
Ponnapati Lourdu

Reputation: 31

What is the best way to audit method variables in java/spring?

I have implemented spring AOP to audit my methods(which would read method parameters and arguments). I am not sure how to audit variables which have been declared inside a method. In below example, I want to audit "c" and "name" variables.

public void method1(int a, int b){  
     int c = a+b;  
     String user= "test";  
} 

NOTE: I need both variable name(i.e "c") and it's value( let's say a and b are 3 and 4 respectively) i.e 7 and similarly variable name(i.e "user") and it's value(i.e "test") for my auditing

In my application, let's say I have method called "process(Object... values) / process(Map)" which would take either "varargs" or "map" as it's argument(process() method definition is upto us). So, we need to pass the variables that we want to audit to this process() method.

My approach:

 public void method1(int a, int b){  
     int c = a+b;  
     String user= "test"; 

    // logic to send variables to process method
    Map<String, Object> myMap = new HashMap<>();
    myMap.put("c",c); 
    myMap.put("user",name); 
    process(myMap);
} 

The problem with this approach is that developer has to create the map and populate values each time.

Please suggest me if we could do this in an efficient way. Thanks in advance.

Upvotes: 3

Views: 689

Answers (1)

kriegaex
kriegaex

Reputation: 67297

I am not sure how to audit variables which have been declared inside a method.

The simple answer is: you don't! Local variables have their name for a reason - they are local! Besides, some compilers optimise away local variables into constants or other JVM opcodes.

It might make sense to audit the method parameters. This can be done easily using Spring AOP for Spring components' public, non-static methods. If you need to audit non-Spring objects or internal method calls like this.doSomething() or even private methods (bad design, should never be necessary), you can still use full-fledged AspectJ from within your Spring application.

Upvotes: 2

Related Questions