Implementing Logging With AOP In Spring

Implementing a Logging Mechanism with Aspect-Oriented Programming in Spring helps teams observe application behaviour without filling controllers, services, and repositories with repeated logging statements. Aspect-Oriented Programming, commonly called AOP, separates cross-cutting concerns such as audit trails, performance measurements, and error reporting from business logic.

This approach is especially useful in Spring applications that expose REST APIs, process payments, or connect to external services. A Melbourne retailer, for example, may need to trace an order from checkout through inventory and delivery systems while keeping the core order service readable.

Spring AOP uses proxies to intercept method calls that match a chosen pointcut. An aspect can then run logic before a method, after it returns, or when it throws an exception. The same mechanism works in applications deployed across Sydney, Brisbane, Perth, or regional Australian environments.

Logging still requires judgement. Australian organisations may handle personal information covered by the Privacy Act, so request payloads, email addresses, tokens, and payment details should never be written casually to log files.

Why AOP Suits Application Logging

AOP is a good fit when the same diagnostic behaviour applies to many methods. Instead of adding logger.info() to every service operation, an aspect can intercept methods annotated with @Loggable. This keeps domain code focused on validation, persistence, and business rules.

Spring AOP is generally proxy-based, so it works best when a method is called through a Spring-managed bean. A private method, a static method, or an internal call using this.someMethod() will not normally pass through the proxy and therefore will not trigger the aspect.

The approach is valuable for request tracing, execution timing, method arguments, successful results, and exceptions. It should complement structured application logs rather than replace proper monitoring, metrics, or distributed tracing.

Configuring Spring AOP

For a Maven project, add the Spring Boot starter:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Spring Boot usually enables proxy support automatically when this dependency is present. In a plain Spring application, add @EnableAspectJAutoProxy to a configuration class. Use SLF4J through a logger such as Logback, which is the default logging implementation in many Spring Boot projects.

Choose the interception scope carefully. A broad pointcut covering every method can create excessive output and increase storage costs, which matters when logs are shipped from an Australian production region to a central observability platform.

Defining A Useful Logging Annotation

A custom annotation gives developers explicit control over which operations deserve detailed logging:

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

The annotation can be placed on service methods that represent meaningful business actions:

@Loggable
public PaymentReceipt processPayment(Order order) {
    return paymentGateway.charge(order);
}

This is usually clearer than matching every method in a package. It also avoids logging low-value getters, mapper methods, and framework callbacks.

Writing The Logging Aspect

An aspect combines the annotation with an @Around advice. The advice can record the start time, continue the method with proceed(), and log either the result or the exception.

@Aspect
@Component
public class LoggingAspect {

    private static final Logger log =
            LoggerFactory.getLogger(LoggingAspect.class);

    @Around("@annotation(Loggable)")
    public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        String method = joinPoint.getSignature().toShortString();
        long started = System.nanoTime();

        try {
            Object result = joinPoint.proceed();
            long elapsed = (System.nanoTime() - started) / 1_000_000;

            log.info("method={} status=success durationMs={}",
                    method, elapsed);
            return result;
        } catch (Throwable error) {
            log.error("method={} status=failed errorType={}",
                    method, error.getClass().getSimpleName(), error);
            throw error;
        }
    }
}

The exception is rethrown so normal Spring transaction handling and controller exception handlers continue to work. Logging code should never accidentally change the business outcome of the intercepted operation.

Choosing Useful Log Fields

Structured fields are easier to search than long sentences. Include an operation name, outcome, duration, correlation ID, authenticated principal where appropriate, and a stable business identifier such as an order reference.

Useful fields vary by system, so establish a small logging policy before adding the aspect:

Avoid serialising entire arguments and return objects. A payment object may contain card information, while an authentication request may include a password or access token. Mask sensitive values and apply suitable retention rules for Australian privacy obligations.

Handling Requests And Correlation IDs

Method logging explains what happened inside the application, while a servlet filter or Spring MVC interceptor can attach a correlation ID to each request. Store that ID in the logging context with MDC, then include it in the log pattern or JSON encoder.

For a REST API used by customers in Adelaide and Sydney, this makes it easier to connect a mobile request, service operation, and downstream error. In a multi-instance deployment, send logs to a central platform rather than relying on local container files.

Asynchronous execution needs extra care because MDC values may not automatically travel to another thread. Configure a task decorator or use a tracing library that propagates context. For larger systems, Micrometer Tracing and OpenTelemetry can provide trace and span data beyond what a simple aspect can capture.

Testing And Operating The Aspect

Test the aspect with a Spring test context and a small service bean. Verify that successful calls produce the expected fields, failed calls preserve the original exception, and execution timing is recorded. Add tests confirming that sensitive arguments are excluded or masked.

Production logging should be configured by environment. Development may use readable console output, while production should favour structured JSON, appropriate log levels, rotation, access controls, and central alerting. Australian SaaS teams often need to balance detailed diagnostics with cloud storage costs and data residency requirements.

A practical operating checklist keeps the mechanism reliable:

Used selectively, Spring AOP provides a clean logging layer that supports debugging, audit visibility, and performance analysis without coupling every business method to infrastructure code.