How to Implement Unified Logging with AOP in a Spring MVC Project

This tutorial explains the fundamentals of Aspect Oriented Programming (AOP) and demonstrates how to create a logging aspect in a Spring MVC application, covering AOP terminology, Spring annotations, pointcut expressions, a WebLog DTO, the WebLogAspect implementation, and how to test the logging output via Swagger UI.

macrozheng
macrozheng
macrozheng
How to Implement Unified Logging with AOP in a Spring MVC Project

AOP Overview

Aspect Oriented Programming (AOP) separates cross‑cutting concerns such as logging, reducing coupling and improving reusability.

Key Terminology

Advice – the action to execute (Before, After, AfterReturning, AfterThrowing, Around).

JoinPoint – a point during program execution where advice can be applied.

Pointcut – expression that selects which join points the advice applies to.

Aspect – a combination of advice and pointcut.

Introduction – adding new methods or fields to existing classes without modification.

Weaving – the process of applying aspects to target objects.

Creating an AOP Aspect in Spring

Relevant Annotations

@Aspect – declares a class as an aspect.

@Before, @After, @AfterReturning, @AfterThrowing, @Around – define the type of advice.

@Pointcut – defines the pointcut expression.

Pointcut Expression Example

execution(public * com.macro.mall.tiny.controller.*.*(..))

Log DTO – WebLog

public class WebLog {
    private String description;
    private String username;
    private Long startTime;
    private Integer spendTime;
    private String basePath;
    private String uri;
    private String url;
    private String method;
    private String ip;
    private Object parameter;
    private Object result;
    // getters and setters omitted
}

Aspect Implementation – WebLogAspect

@Aspect
@Component
@Order(1)
public class WebLogAspect {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);

    @Pointcut("execution(public * com.macro.mall.tiny.controller.*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable { /* ... */ }

    @AfterReturning(value = "webLog()", returning = "ret")
    public void doAfterReturning(Object ret) throws Throwable { /* ... */ }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        // obtain HttpServletRequest
        // build WebLog instance, set description, ip, method, parameters, result, timing, etc.
        // log the WebLog as JSON
        return result;
    }

    private Object getParameter(Method method, Object[] args) {
        // extract @RequestBody and @RequestParam values into a list or map
        // return appropriate parameter representation
    }
}

Testing the Aspect

Run the application and open http://localhost:8080/swagger-ui.html. Invoking any controller endpoint prints a JSON log similar to:

{
  "result": { "code":200, "data":{...}, "message":"操作成功" },
  "basePath":"http://localhost:8080",
  "method":"GET",
  "parameter":[{"pageNum":1},{"pageSize":1}],
  "description":"分页查询品牌列表",
  "startTime":1561273191861,
  "uri":"/brand/list",
  "url":"http://localhost:8080/brand/list",
  "spendTime":101
}

Source Code

Repository: https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-aop

Further Reading

mall在Linux环境下的部署(基于Docker Compose)

mall在Linux环境下的部署(基于Docker容器)

mall在Windows环境下的部署

mall整合SpringBoot+MyBatis搭建基本骨架

mall整合Swagger-UI实现在线API文档

mall整合SpringSecurity和JWT实现认证和授权(一)

mall整合Elasticsearch实现商品搜索

mall整合Mongodb实现文档操作

mall整合RabbitMQ实现延迟消息

mall整合OSS实现文件上传

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaaopspringloggingAspect Oriented Programming
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.