Implementing Custom Logging with Spring AOP and Annotations
This article explains how to create a custom logging solution in Spring by defining annotation-based AOP aspects, configuring pointcuts, handling various advice types, and persisting log details such as user, operation, parameters, and results into a database using Java code examples.
When developing a Spring project, simple AOP logging may not capture detailed information such as table names or operation descriptions. To overcome this, the article demonstrates how to define a custom annotation that stores the desired log metadata and how to retrieve it via a Spring AOP aspect.
Spring AOP terminology is introduced, covering Aspect, Joinpoint, Advice, and Pointcut, followed by a list of advice types (@Before, @AfterReturning, @AfterThrowing, @After, @Around) and the two configuration styles (XML and AspectJ annotation).
Custom annotation definition :
package com.ywj.log;
import java.lang.annotation.*;
/**
* AOP日志记录 自定义注解类
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemCrmlog {
/** 日志描述 */
String description() default "";
/** 操作的表名 */
String tableName() default "";
}Aspect class that intercepts methods annotated with @SystemCrmlog, extracts annotation values, request information, and saves a CrmLogMessage entity to the database. It includes handling for different advice types (after throwing, after returning) and demonstrates how to obtain method parameters, signatures, and execution results.
package com.ywj.log;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
@Aspect
@Component
public class SystemLogAspect {
@Pointcut("@annotation(com.ywj.log.SystemCrmlog)")
public void crmAspect() {}
@AfterThrowing(value="crmAspect()", throwing="ex")
public void afterThrowingMethod(JoinPoint joinPoint, Exception ex) throws Exception {
// build and persist CrmLogMessage for exception case
}
@AfterReturning(value="crmAspect()", returning="returnValue")
public void doCrmLog(JoinPoint joinPoint, Object returnValue) throws Exception {
// build and persist CrmLogMessage for normal return case
}
// helper methods to extract annotation values, parameters, etc.
private String getServiceMthodDescription(JoinPoint joinPoint) throws Exception { /* ... */ }
private String getServiceMthodTableName(JoinPoint joinPoint) throws Exception { /* ... */ }
private String getServiceMthodParams(JoinPoint joinPoint) throws Exception { /* ... */ }
public HttpServletRequest getHttpServletRequest() { /* ... */ }
}The article also provides the CrmLogMessage POJO that represents the log record, a WebUtil helper to fetch the current user from the session, and the necessary Spring XML configuration to enable @AspectJ support and component scanning.
<!-- Enable @AspectJ support -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- Scan aspect package -->
<context:component-scan base-package="com.ywj.log"/>
<!-- Scan business implementation packages -->
<context:component-scan base-package="com.*.*.biz.impl"/>Finally, an example of applying the custom annotation to a service method is shown:
@SystemCrmlog(description = "进行了登录操作", tableName = Constans.USER_TABLENAME)
public void login(...) { /* ... */ }Overall, the guide walks readers through building a reusable, annotation‑driven logging mechanism in Spring, covering both the conceptual AOP background and the concrete Java implementation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
