2

I'm working on a Spring Boot API that's supposed to be deployed later this month. We created our own interface for a repository, and extended the CrudRepository. Spring boot autowires everything.

What I would like to do is add more logging capabilities, such as LOGGER.info("searched for solution ID").

Currently our code looks like this:

@Repository
public interface ProductSolutionRepository extends CrudRepository<ProductSolution, String> {

    public List<ProductSolution> findBySolutionId(@Param("solutionId") int solutionId);

Since Spring configures everything don't really see a way of decorating these functions to add logging functionality. Can someone help me out by pointing me to the documentation, showing a nice example, or explaining the concept behind logging decorators?

rmeertens
  • 4,383
  • 3
  • 17
  • 42

2 Answers2

4

First, I would like to point out some redundant codes for you.

  • You don't need to annotate the repository with @Repository, spring boot can autowire it automatically.
  • @Param is used when you write a sql with @Query, you just need to declare your parameters here.

The repository is the dao layer. A normal practice, you should create a service for each repository and autowire the repository into the service. Then you can implement transaction or write logs there.

Dave Pateral
  • 1,415
  • 1
  • 14
  • 21
3

You can use a single file AOP Logging Aspect using AspectJ cutting across your repository interfaces layer and logging method name, input args and output.

Assuming for this purpose a RepositoryLoggingAspect class, you'd have to annotate it first with @Aspect:

import org.aspectj.lang.annotation.Aspect;

@Aspect
public class RepositoryLoggingAspect {
//..
}

And then create a Pointcut aiming at your repository package you want to cut-accross:

@Pointcut("within(package.of.my.repositories..*)")
public void repositoriesPackagePointcut() {}

And finally define the logging logic in an @Around annotated method:

@Around("repositoriesPackagePointcut()")
public Object logMyRepos(ProceedingJoinPoint joinPoint) throws Throwable {
  //log method name using: joinPoint.getSignature().getName()
  //log method arguments using: Arrays.toString(joinPoint.getArgs())
  //store and log method output using: Object myResult = joinPoint.proceed();
}
dimitrisli
  • 20,895
  • 12
  • 59
  • 63