This article is SpringBoot through AOP to implement system logging (2) -Service layer log monitoring, if you want to implement the Controller layer monitoring, please click portal:
SpringBoot implements system logging through AOP (1) -Controller layer log monitoring (including log table design)
Due to the company’s business requirements, it is necessary to perform log performance monitoring for the entire system, so that developers can quickly locate system bottlenecks and solve problems. The relevant codes are as follows:
1. Introduce dependencies
<! <dependency> <groupId>org.springframework.boot</groupId> <artifactId> spring-boot-starter-AOP </artifactId> </dependency>Copy the code
ServiceMonitor monitors annotations
/ * * *@Description: Service monitoring annotation *@Author: zhangzhixiang
* @CreateDate: 2018/12/09 12:34:56
* @Version1.0 * /
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceMonitor {
String value(a) default "";
}
Copy the code
3. Service layer code
/ * * *@Description: Batch upload public interface *@Author: zhangzhixiang *@CreateDate: 2018/08/31 16:39:54 *@Version: 1.0 * /
@Service
public class ExcelParseServiceImpl implements ExcelParseService {
private static final Logger logger = LoggerFactory.getLogger(ExcelParseServiceImpl.class);
@Override
@ServiceMonitor
public ExcelParseResultBO excleParse(String fileName, String code, String model) {
// Omit the logical code here}}Copy the code
ServiceMonitor log monitor interceptor
/ * * *@Description: log monitoring interceptor *@Author: zhangzhixiang *@CreateDate: 2018/12/09 12:34:56 *@Version: 1.0 * /
@Aspect
@Component
public class ServiceLogAspect {
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
private final Logger logger = LoggerFactory.getLogger(this.getClass);
//1. Configure the matching ServiceMonitor annotation expression
@Pointcut("@annotation(com.cy.ops.api.common.annotation.ServiceMonitor)")
public void serviceLog(a) {}
@Around(value = "serviceLog()")
public Object doArount(ProceedingJoinPoint joinPoint) throws Throwable {
//2. Record the execution time
long startTime = System.currentTimeMillis();
Object result = joinPoint.proceed(joinPoint.getArgs());
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
//3. Log method name
String methodName = joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()";
logger.info("* * * * * * * * * * Method: {}, Start: {}, End: {}, Total: {} ms * * * * * * * * * *",methodName, dateFormat.format(startTime), dateFormat.format(endTime), totalTime);
returnresult; }}Copy the code
With the above code, we can happily monitor how much time the service method consumes. If you want to print more parameters, you can extend it in the ServiceLogAspect.
The whole article is completely pure hand, if you feel helpful, remember to pay attention to praise yo ~~