springboot 动态日志管理(actuator)

本文介绍了如何在SpringBoot项目中使用ActuatorAPI来访问和管理日志文件,包括自定义Controller处理logfile请求,配置文件设置web接口暴露日志,以及调整特定目录的日志级别。

引入依赖

         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
​

其次,创建一个自定义的Controller类,该类处理/actuator/logfile路由的请求。可以参考以下示例代码:

import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
 
@RestController
public class LogFileController {
    
    @GetMapping(value = "/actuator/logfile", produces = MediaType.TEXT_PLAIN_VALUE)
    public String getLogFile() throws Exception {
        Resource resource = new ClassPathResource("logs/application.log"); // 指定日志文件路径
        
        byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
        return new String(bytes, StandardCharsets.UTF_8);
    }
}

上述代码中,我们假设日志文件位于classpath根目录下的"logs/"子目录中,名称为"application.log"。你可以根据实际情况修改路径和文件名。

最后,重新编译、构建和部署应用程序,然后就可以通过访问http://localhost:8080/actuator/logfile来查看历史日志文件的内容了。

配置文件添加

management.endpoints.web.exposure.include= loggers

之后访问http://localhost:8080/xxx/actuator/loggers

即可看到每个文件的日志级别

查看某个目录的日志级别

http://localhost:8080/xxx/actuator/loggers](http://localhost:8080/rose-server/actuator/loggers/{目录名}

可以配置指定目录的日志级别

post请求修改指定目录日志级别:

http://localhost:8080/xxx/actuator/loggers/{目录名}

请求提

{
"configuredLevel": "debug"
}

再次查看此目录的日志级别发现已被修改

http://localhost:8080/xxx/actuator/loggers](http://localhost:8080/rose-server/actuator/loggers/{目录名}

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值