@RequestMapping(“/log”)
public class LogFileWebEndpoint {
@Value(“${laker.log.file.path:./laker.log}”)
String filePathConfig;
@RequestMapping(value = “/file”, produces = “text/plain; charset=UTF-8”)
public Resource logFile(@RequestParam(required = false) String filePath) {
if (StrUtil.isNotBlank(filePath)) {
filePathConfig = filePath;
}
Resource logFileResource = new FileSystemResource(new File(filePathConfig));
if (logFileResource == null || !logFileResource.isReadable()) {
return null;
}
return logFileResource;
}
}
浏览器访问:http://localhost:8080/log/file?filePath=d://a.log
结果如下:
这里跟动态配置没什么关系,但是这个功能还是蛮实用的,你别跟我说上什么
ELK套件
,其实大部分场景,压根没几台实例,杀鸡焉用牛刀。几行代码实现这个在线weblog,瑞士军刀,小而实用它不香吗?
2. 实现日志级别查询
核心代码:
@Autowired
private LoggingSystem loggingSystem;
@Autowired
private LoggerGroups loggerGroups;
Logger log = LoggerFactory.getLogger(LogWebEndpoint.class);
@RequestMapping(value = “/loggers”) //返回所有日志以及配置的级别
public Map<String, Object> loggers() {
Collection configurations = this.loggingSystem.getLoggerConfigurations();
if (configurations == null) {
return Collections.emptyMap();
}
Map<String, Object> result = new LinkedHashMap<>();
result.put(“levels”, getLevels());
result.put(“loggers”, getLoggers(configurations));
result.put(“groups”, getGroups());
return result;
}
浏览器访问:http://localhost:8080/log/loggers
结果如下:
3. 实现日志的级别动态设置
@RequestMapping(value = “/level”) //动态设置日志级别
public void configureLogLevel(String name, @Nullable LogLevel configuredLevel) {
log.debug(“name:{},level:{}”, name, configuredLevel);
log.info(“name:{},level:{}”, name, configuredLevel);
log.warn(“name:{},level:{}”, name, configuredLevel);
log.error(“name:{},level:{}”, name, configuredLevel);
LoggerGroup group = this.loggerGroups.get(name);
if (group != null && group.hasMembers()) {
group.configureLogLevel(configuredLevel, this.loggingSystem::setLogLevel);
return;
}
this.loggingSystem.setLogLevel(name, configuredLevel);
}
默认是
INFO
级别
- 浏览器请求:http://localhost:8080/log/level?name=com.laker.config&configuredLevel=DEBUG
- 浏览器请求:http://localhost:8080/log/level?name=com.laker.config&configuredLevel=ERROR
从结果可以看出已经动态生效
其他方案:动态态修改日志配置文件
修改logback.xml配置文件:在configuration根节点配置属性scan和scanPeriod,scan为true时,配置文件被修改会被重新加载,scanPeriod定义了扫描文件变化的周期,默认60000毫秒,即一分钟。
…
重点来了 ,通过上面的代码和演示我们已经知道动态刷新日志级别核心代码。
loggingSystem.setLogLevel(name, configuredLevel);
再结合着前面讲的Nacos长连接监听远端配置变更,很容易就可以实现动态设置了。