简介
spring-boot-actuator是springboot的一个监控工具,它可以以http或JMX的方式暴露一些endPoint,内置的endpoint有 health,info,beans,loggers等。
我们可以通过loggers来动态调整日志级别,无需重启服务。
如果是想使用webEndPoint的话,项目必须包含web-starter相关的依赖,因为actuator 的httpEndPoint是以mvc的方式集成的。
使用
1.在pom文件中引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
</dependency>
2.在配置文件中开启loggers的endPoint端点
# 还可以配置默认路径以及修改路径名称等
management:
endpoints:
web:
exposure:
include: loggers
3.使用请求查看或者修改日志等级(也可以使用postman等方式)
$ curl 'http://localhost:8080/actuator/loggers/com.example' -i -X POST \
-H 'Content-Type: application/json' \
-d '{"configuredLevel":"debug"}'
简单的封装使用
@Slf4j
@RestController
@RequestMapping("/all-loggers")
public class LoggersController {
@Resource
private LoggersService loggersService;
/**
* 获取所有服务下的日志等级配置信息
*
* @return
*/
@GetMapping
public HttpBody getAllApplicationLoggersLevelInfo() {
LoginAccountInfo loginAccountInfo = SessionContextHolder.getAccountAndValid();
log.info("{}查询日志级别", loginAccountInfo.getUserName());
return HttpBody.getSucInstance(loggersService.getAllApplicationLoggersLevelInfo());
}
@PostMapping
public HttpBody updateApplicationLoggersLevel(@RequestBody List<LoggerRequest> request) {
LoginAccountInfo loginAccountInfo = SessionContextHolder.getAccountAndValid();
log.info("当前用户正在操作日志级别:{},请求参数为:{}",loginAccountInfo,request);
loggersService.updateLoggersLevel(request);
return HttpBody.SUCCESS;
}
}
public interface LoggersService {
Map<String, String> getAllApplicationLoggersLevelInfo();
void updateLoggersLevel(List<LoggerRequest> request);
}
@Service
@Slf4j
public class LoggersServiceImpl implements LoggersService {
@Override
public Map<String, String> getAllApplicationLoggersLevelInfo() {
Map<String, String> map = new HashMap<>();
for (ApplicationEnum applicationEnum : applicationEnum.values()) {
map.put(applicationEnum.getCode(), HttpUtil.get(applicationEnum.getUrl()));
}
return map;
}
@Override
public void updateLoggersLevel(List<LoggerRequest> request) {
if (CollUtil.isNotEmpty(request)) {
request.forEach(logger -> {
ApplicationEnum enumByCode = ApplicationEnum.getEnumByCode(logger.getApplicationKey());
if (ObjectUtil.isNotNull(enumByCode)) {
Map<String, String> param = new HashMap<>();
param.put("configuredLevel", StrUtil.isNotBlank(logger.getLevel()) ? logger.getLevel() : enumByCode.getDefaultLevel());
String post = HttpUtil.post(enumByCode.getUrl() + (StrUtil.isNotBlank(logger.getPackageName()) ? logger.getPackageName() : enumByCode.getDefaultPackage()), JSON.toJSONString(param));
log.info("日志级别动态调整返回结果打印{}", post);
} else {
log.info("未找到对应application:{}", logger.getApplicationKey());
}
});
}
}
}