머리말
오늘 변비가 있습니까? 프로그래머는 오래 앉아 있으면 정말 변비에 걸립니다. 이 작은 건조물을 실수로 클릭하면 물 한 컵을 마시고 화장실에 가십시오. 왼손으로 잡고 조준하고 휴대폰을 스와이프하십시오. 이 기사를 끝까지 읽으려면 오른손을 바.
성취하다
이 글에서 AOP 통합 로그 관리의 작성 방식은 잘 알려진 해외 오픈소스 프레임워크인 JHipster의 AOP 로그 관리 방식에서 따왔다.
1. 종속성 소개
<!-- spring aop -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2. 로그백 구성 정의
1) 개발 및 테스트 환경의 spring-web 패키지는 로그 수준을 INFO로 정의하고 프로젝트 패키지는 로그 수준을 DEBUG로 정의하고 2)
prod 환경의 spring-web 패키지는 로그 수준을 ERROR로 정의합니다. 프로젝트 패키지는 로그 수준을 INFO로 정의합니다.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml" />
<logger name="org.springframework.web" level="INFO"/>
<logger name="org.springboot.sample" level="TRACE" />
<springProfile name="dev,test">
<logger name="org.springframework.web" level="INFO"/>
<logger name="org.springboot.sample" level="INFO" />
<logger name="com.example.aoplog" level="DEBUG" />
</springProfile>
<springProfile name="prod">
<logger name="org.springframework.web" level="ERROR"/>
<logger name="org.springboot.sample" level="ERROR" />
<logger name="com.example.aoplog" level="INFO" />
</springProfile>
</configuration>
3. 패싯 클래스 작성
1) springBeanPointcut(): 별도 정의된 Spring 프레임워크 진입점
2) applicationPackagePointcut(): 별도 정의된 프로젝트 패키지 진입점
3) logAfterThrowing(): 1과 2로 정의된 진입점에서 예외 발생 시 로그 형식
4), logAround(): 1과 2로 정의된 진입점 방법이 들어오고 나갈 때 로그 형식과 내용을 표시합니다 .
package com.example.aoplog.logging;
import com.example.aoplog.constants.GloablConstants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.stereotype.Component;
import java.util.Arrays;
/**
* <p>
* AOP统一日志管理 切面类
* </p>
*
* @author 福隆苑居士,公众号:【Java分享客栈】
* @since 2022/5/5 21:57
*/
@Aspect
@Component
public class LoggingAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final Environment env;
public LoggingAspect(Environment env) {
this.env = env;
}
/**
* 匹配spring框架的repositories、service、rest端点的切面
*/
@Pointcut("within(@org.springframework.stereotype.Repository *)" +
" || within(@org.springframework.stereotype.Service *)" +
" || within(@org.springframework.web.bind.annotation.RestController *)")
public void springBeanPointcut() {
// 方法为空,因为这只是一个切入点,实现在通知中。
}
/**
* 匹配我们自己项目的repositories、service、rest端点的切面
*/
@Pointcut("within(com.example.aoplog.repository..*)"+
" || within(com.example.aoplog.service..*)"+
" || within(com.example.aoplog.controller..*)")
public void applicationPackagePointcut() {
// 方法为空,因为这只是一个切入点,实现在通知中。
}
/**
* 记录方法抛出异常的通知
*
* @param joinPoint join point for advice
* @param e exception
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
// 判断环境,dev、test or prod
if (env.acceptsProfiles(Profiles.of(GloablConstants.SPRING_PROFILE_DEVELOPMENT, GloablConstants.SPRING_PROFILE_TEST))) {
log.error("Exception in {}.{}() with cause = '{}' and exception = '{}'", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
} else {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
}
/**
* 在方法进入和退出时记录日志的通知
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
}
4. 테스트
1) 서비스 작성
package com.example.aoplog.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/**
* <p>
* AOP统一日志管理测试服务
* </p>
*
* @author 福隆苑居士,公众号:【Java分享客栈】
* @since 2022/5/5 21:57
*/
@Service
@Slf4j
public class AopLogService {
public String test(Integer id) {
return "传入的参数是:" + id;
}
}
2) 컨트롤러 작성
package com.example.aoplog.controller;
import com.example.aoplog.service.AopLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
* 测试接口
* </p>
*
* @author 福隆苑居士,公众号:【Java分享客栈】
* @since 2022/4/30 11:43
*/
@RestController
@RequestMapping("/api")
@Slf4j
public class TestController {
private final AopLogService aopLogService;
public TestController(AopLogService aopLogService) {
this.aopLogService = aopLogService;
}
@GetMapping("/test/{id}")
public ResponseEntity<String> test(@PathVariable("id") Integer id) {
return ResponseEntity.ok().body(aopLogService.test(id));
}
}
3) 환경 설정
여기 개발자를 시도하고, 제품을 직접 사용해 보시겠습니까? 안 받아주면 주먹으로 때리고 울겠다!
server:
port: 8888
# 环境:dev-开发 test-测试 prod-生产
spring:
profiles:
active: dev
4) 효과
나는 나 자신을 설명하지 않는다
예외를 시도하고 수동으로 예외를 추가하십시오.
@Service
@Slf4j
public class AopLogService {
public String test(Integer id) {
int i = 1/0;
return "传入的参数是:" + id;
}
}
효과
요약하다
좋아요! 을 그만하기로하다!
링크: https://pan.baidu.com/doc/share/flr0QYwZYPYxmWSRPbnJRw-1028798558141759
추출 코드: bxaa
마음 에 안든다 , 북마크 하지마 , 팔로우 하지마세요 , 화장실가서 물한잔 마시고 오늘 퇴근전에 뽑아주시면 만족하겠습니다.