Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
Expand Down
35 changes: 35 additions & 0 deletions src/main/java/com/app/config/ApplicationLogging.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.app.config;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we used it through Annotation if we don't want to log entry exit for all methods then annotation also works better at that time just annotate a particular method.

annotation implementation
@aspect
@component
@order(1)
@slf4j
@SuppressWarnings("PMD.AvoidCatchingGenericException")
public class LoggingInterceptor
{

/**
 * StringBuilder message buffer init size.
 */
public static final int INIT_CAPACITY = 100;

/**
 * Interceptor method for methods.
 *
 * @param joinPoint The join point for the intercepted method.
 * @return Object
 * @throws Throwable Exceptions thrown by the intercepted method.
 */
@Around("@within(LogEntryAndExit) || @annotation(LogEntryAndExit)")
public Object intercept(final ProceedingJoinPoint joinPoint) throws Throwable
{
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    String methodName = method.getName();
    String className = method.getDeclaringClass().getSimpleName();
    String parameters = getParameters(method);
    log.info("Entering {}:{}({})", className, methodName, parameters);
    Object out;

    try
    {
        out = joinPoint.proceed();
    } catch (Exception t)
    {
        logExceptions(t, method);
        throw t;
    } finally
    {
        log.info("Exiting {}:{}", className, methodName);
    }

    return out;
}

/**
 * Logging exceptions.
 *
 * @param t Exception to be logged.
 * @param method Method to me logged.
 */
private void logExceptions(final Throwable t, final Method method)
{
    String exceptionName = t.getClass().getSimpleName();
    String methodName = method.getName();
    String className = method.getDeclaringClass().getSimpleName();
    String parameters = getParameters(method);
    String message = String.format("\n%s thrown from %s:%s(%s)\n%s", exceptionName, className, methodName,
            parameters, t.getMessage());

    if (log.isDebugEnabled())
    {
        log.error(message, t);
    }
    else
    {
        log.error(message);
    }
}

/**
 * Get method parameters.
 *
 * @param method Method to be logged.
 * @return String
 */
private String getParameters(final Method method)
{
    StringBuilder sb = new StringBuilder(INIT_CAPACITY);

    Parameter[] params = method.getParameters();
    if (params.length > 0)
    {
        for (Parameter param : params)
        {
            if (param != null)
            {
                sb.append(param.getType().getSimpleName()).append(' ').append(param.getName()).append(", ");
            }
        }

        // remove trailing parameter separator
        sb.delete(sb.length() - 2, sb.length());
    }

    return sb.toString();
}

}
annotation code:-
@documented
@retention(RetentionPolicy.RUNTIME)
@target({ElementType.METHOD, ElementType.TYPE })
public @interface LogEntryAndExit
{

}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@LogEntryAndExit will work now on methods


import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Log4j2
public class ApplicationLogging {

@Pointcut("within(com.app..*) && !within(com.app.config..*)")
public void applicationPackagePointcut() {
// Pointcut to capture all methods within the specified package
}

@Before("applicationPackagePointcut()")
public void logMethodEntry(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getSimpleName();
Object[] args = joinPoint.getArgs();
log.info("Entering method: {}.{}() with arguments: {}", className, methodName, args);
}

@AfterReturning(pointcut = "applicationPackagePointcut()", returning = "result")
public void logMethodExit(JoinPoint joinPoint, Object result) {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getSimpleName();
log.info("Exiting method: {}.{}() with result: {}", className, methodName, result);
}
}