How to Write a Logging Aspect in Spring AOP Step by Step
Write a logging aspect with Spring AOP: add the starter, define pointcuts for services, log arguments, results and failures, and avoid leaking data.

A logging aspect records what a layer of your application does without putting a log statement in every method. It is the standard first use of Spring AOP, and it goes wrong in predictable ways: it logs passwords, it adds noise to hot methods, and it silently does nothing for calls inside the same class. This post writes one on Spring Boot 4, Spring Framework 7 and JDK 25, then covers the limits of proxy-based AOP, so you know when to leave the aspect out.
The dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>The starter pulls in AspectJ's weaver and the annotation library. Boot enables auto-proxying when AspectJ is on the classpath, so no @EnableAspectJAutoProxy is required. If an aspect never fires, check this dependency first; without it the class compiles and does nothing.
The aspect
@Aspect
@Component
public class ServiceLoggingAspect {
private static final Logger log = LoggerFactory.getLogger(ServiceLoggingAspect.class);
@Around("within(com.example..service..*)")
public Object logCall(ProceedingJoinPoint pjp) throws Throwable {
var signature = pjp.getSignature().toShortString();
long start = System.nanoTime();
try {
Object result = pjp.proceed();
log.debug("{} returned in {} ms", signature, elapsedMs(start));
return result;
} catch (Throwable ex) {
log.warn("{} failed after {} ms: {}", signature, elapsedMs(start), ex.toString());
throw ex;
}
}
private static long elapsedMs(long startNanos) {
return (System.nanoTime() - startNanos) / 1_000_000;
}
}@Aspect declares the class as an aspect, and @Component registers it as a bean, because Spring AOP only applies aspects that are beans. @Around wraps the method call. The advice must call proceed() or the target never runs, and it must return the result, or the caller gets null. It rethrows the exception so behaviour does not change: swallowing it in a logging aspect is a classic bug that turns failures into silent nulls.
The log message uses placeholders instead of string concatenation, so arguments are not formatted when the level is disabled. Log the exception's toString() at the aspect and leave the stack trace for the place that finally handles it. Logging a stack trace in both places produces two copies per failure.
Pointcut expressions you will use
The string in @Around is a pointcut: it selects which methods are advised.
| Expression | Selects |
|---|---|
within(com.example..service..*) | Every method of every class in any service package |
execution(* com.example.orders.OrderService.*(..)) | All methods of one class |
@annotation(com.example.logging.Audited) | Methods that carry your own annotation |
@within(org.springframework.stereotype.Service) | Every method of a @Service class |
bean(*Repository) | Beans whose name ends in Repository |
For anything beyond the simplest case, prefer a custom annotation. An explicit @Audited on a method is visible to the reader, discoverable by search and easy to remove. A package expression, on the other hand, advises code that nobody marked, and a new class in the package is logged without anyone deciding so. A named pointcut keeps expressions out of the advice:
@Pointcut("within(com.example..service..*)")
void serviceLayer() { }
@Around("serviceLayer() && !@annotation(com.example.logging.NoLog)")
public Object logCall(ProceedingJoinPoint pjp) throws Throwable { /* ... */ }The full grammar is in the pointcut reference.
Arguments, with care
pjp.getArgs() returns the arguments, and logging them is tempting. Think before you do. Arguments carry passwords, tokens, card numbers and personal data, and a debug line written once is retained for months in a log store with wider access than your database. Log argument types or identifiers, or log nothing:
Object[] args = pjp.getArgs();
String ids = Arrays.stream(args)
.filter(a -> a instanceof Long || a instanceof UUID)
.map(String::valueOf)
.collect(Collectors.joining(","));A parameter annotation such as @Sensitive, checked through MethodSignature.getMethod().getParameterAnnotations(), lets you mask by declaration, not by guess. This links to the checklist in security before release. Return values deserve the same treatment: log that something returned, and its size if useful, not its contents.
What it costs
An advised call goes through a proxy and an interceptor chain, and for @Around with a ProceedingJoinPoint that is a few hundred nanoseconds of overhead plus the logging itself. For service methods that reach a database, the overhead is not measurable. For a method called millions of times per second, such as a getter or a hot loop helper, do not advise it. The isDebugEnabled() guard is unnecessary for placeholder logging but useful if you build the message from computed values. Timing logic with its own concerns is in timing aspects.
Limits of proxy-based AOP
Spring AOP works by wrapping beans in proxies, so it only sees calls that go through the proxy. Three consequences follow.
A method that calls another method on this bypasses the proxy, so the second method is not advised. This self-invocation problem is the reason a logging aspect seems to miss calls, and it is described in self-invocation.
Only public methods on Spring beans are advised with the default proxies. Private, package-private and static methods are not, and neither are objects you created with new.
Final classes and final methods cannot be proxied by subclassing. Spring uses interface proxies or CGLIB, and CGLIB fails on a final class. If you need to advise calls inside the same class, private methods or objects outside the container, use full AspectJ with load-time or compile-time weaving; the trade-off is explained in AOP versus AspectJ.
Correlation across the call chain
A line per method is only useful if you can tell which request it belongs to. Put a request id in the MDC from a servlet filter, and include %X{requestId} in the log pattern. The aspect then needs no extra work, and every advised call carries the id. Nested calls can be shown by incrementing a thread-local depth counter in the aspect and indenting the message, which helps when reading a single trace and is wrong for a log store that sorts lines across threads. If you reach for that, you probably want tracing rather than logging, and Micrometer Tracing gives spans with durations for the same boundaries without a custom aspect.
Order matters when several aspects apply. @Transactional, security and your logging aspect are all advice on the same method. Use @Order on the aspect to choose where it sits: with the highest precedence it logs the time including transaction commit, and with the lowest it times only the method body. Pick deliberately, and write the choice in a comment, because the log timings will be compared with database timings later.
Testing the aspect
@SpringBootTest(classes = {OrderService.class, ServiceLoggingAspect.class})
@ExtendWith(OutputCaptureExtension.class)
class ServiceLoggingAspectTest {
@Autowired OrderService service;
@Test
void logs_a_failure_and_rethrows(CapturedOutput output) {
assertThrows(IllegalStateException.class, () -> service.cancelShipped(7L));
assertThat(output).contains("cancelShipped").contains("failed after");
}
}The test uses the real proxy, which is the point: a unit test that instantiates the aspect by hand proves nothing about whether Spring applies it. Checking log output in tests is covered in asserting on log output.
When not to write one
If you need only request-level logging, a servlet filter or Spring's CommonsRequestLoggingFilter is simpler and sees the HTTP data. If you need metrics, Micrometer's @Timed and observation support already do this. Write an aspect when the behaviour is about method calls, such as auditing who invoked which service method, and you want it declared in one place. The authoritative description of the model is the Spring AOP chapter.


