第三次 日志、错误码、异常处理设计文档
文章目录
- T31作业目录
- 前言
- 一、日志设计
- 二、错误码设计
- 三、异常处理设计
- 总结
前言
T31作业
一、日志设计
springboot默认是用logback的日志框架的,项目中使用log4j2更高性能的日志框架则需排除logback,不然会出现jar依赖冲突的报错。
org.springframework.boot spring-boot-starter-web spring-boot-starter-logging org.springframework.boot org.springframework.boot spring-boot-starter-log4j2 com.lmax disruptor ${disruptor.version}
使用AsyncLogger模式来实现日志的异步打印(性能更优)。
配置文件:(rosources目录下)log4j2-spring.xml
%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %t %c - %m%n %d{yyy-MM-dd HH:mm:ss} %style{[%15t]}{bright,blue} %clr{%-5level}%style{%logger{80}}{cyan} %style{[%L]}{magenta} - %msg%n UTF-8 500MB
Log4j2中的同步日志与异步日志
配置读取yml配置文件的属性值:将原先的logback.xml改成logback-spring.xml。原因是springboot先读取logback.xml,然后加载yml/properties,再加载logback-spring.xml
读取配置文件的日志路径 LoggingListener.java
@Component
@Slf4j
public class LoggingListener implements ApplicationListener, Ordered {
private final static String LOG_PATH = "log.path";
private final static String APP_NAME = "app.name";
private final static String SPRING_LOG_PATH_PROP = "logging.file.path";
private final static String SPRING_APP_NAME_PROP = "spring.application.name";
@Override
public void onApplicationEvent(ApplicationEvent applicationEvent) {
if (applicationEvent instanceof ApplicationEnvironmentPreparedEvent) {
ConfigurableEnvironment environment = ((ApplicationEnvironmentPreparedEvent) applicationEvent).getEnvironment();
log.info("event:{}","ApplicationEnvironmentPreparedEvent");
refreshLog(environment);
}else if(applicationEvent instanceof ContextRefreshedEvent){
Environment environment = ((ContextRefreshedEvent) applicationEvent).getApplicationContext().getEnvironment();
log.info("event:{}","ContextRefreshedEvent");
refreshLog(environment);
}
}
private void refreshLog(Environment environment){
String filePath = environment.getProperty(SPRING_LOG_PATH_PROP);
log.info("filePath:{}",filePath);
if (filePath != null && !filePath.isBlank()) {
System.setProperty(LOG_PATH,filePath);
MDC.put(LOG_PATH,filePath);
}
log.info("filePath:{}",filePath);
String appName = environment.getProperty(SPRING_APP_NAME_PROP);
if (appName != null && !appName.isBlank()) {
System.setProperty(APP_NAME,appName);
MDC.put(APP_NAME,appName);
}
}
@Override
public int getOrder() {
// 当前监听器的启动顺序需要在日志配置监听器的前面,所以此处减 1
return LoggingApplicationListener.DEFAULT_ORDER - 1;
}
}
DemoApplication.java启动文件修改
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class DemoApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(DemoApplication.class);
// 添加 日志监听器,使 log4j2-spring.xml 可以间接读取到配置文件的属性
application.addListeners(new LoggingListener());
application.run(args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
二、错误码设计
三、异常处理设计
参考:SpringBoot 之配置全局异常处理器捕获异常
总结顶住。我们能赢!!!



