Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep record of what users do in Spring MVC

I have a very large application written in Spring MVC. I want to keep an "activity record" that tracks into a database what users do in my application.

In the first stage I just want an activity log, it can be just a list of the controller methods that get called during user's actions, but later on I would like this info to be more "human readable", i.e. instead of "modifyAccount(accountId = 5, accountBalance =500) something like "user X updates balance for account 5 to 500".

The problem I see is, since my application is very large, I would not like to modify each of my actions to add this logging mechanism. Is there a more flexible, declarative way to do this?

like image 683
Gabriel Sanmartin Avatar asked Jan 12 '23 17:01

Gabriel Sanmartin


1 Answers

You can make use of Aspect Oriented Programming (AOP) to automate the logging.

http://static.springsource.org/spring/docs/2.0.8/reference/aop.html

In the above page shows many examples on how to use AOP with spring. One example is the use of annotations to find methods you're interested in. The use of such annotation is an easy way to determine what methods should be logged.

The @Audit annotation

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Auditable {
    ...
}

The auditing method

@After("@annotation(auditable)", argNames="joinPoint")
public void audit(JoinPoint joinPoint) {
    logger.info("Called {} with arguments {}", 
        joinPoint.getSignature().getLongString(), joinPoint.getArgs());
}

I did not test this code but it gets the point across.

like image 196
Bart Avatar answered Jan 20 '23 05:01

Bart