🚀 Add AOP-based Logging for Method Entry & Exit in Spring Boot Application#14
Open
🚀 Add AOP-based Logging for Method Entry & Exit in Spring Boot Application#14
Conversation
mdakib9758
reviewed
Jul 4, 2025
| @@ -0,0 +1,35 @@ | |||
| package com.app.config; | |||
There was a problem hiding this comment.
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
{
}
There was a problem hiding this comment.
@LogEntryAndExit will work now on methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Overview
This PR introduces application-wide logging using Spring AOP to track method executions within the
com.apppackage. The implementation ensures better visibility into method calls, arguments, and return values.Changes Introduced
@Aspect-based logging inApplicationLoggingclass.@Pointcutto capture method executions across the application while excluding configuration classes.@Beforeand@AfterReturningto log method entry and exit.@Log4j2for structured logging.Why this is needed?
How to Test?
com.apppackage.