springboot中動態修改logback日誌級別web
在spring boot中使用logback日誌時,項目運行中,想要修改日誌級別。spring
代碼以下:springboot
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class LogbackController { private Logger log = LoggerFactory.getLogger(LogbackController.class); @RequestMapping(value = "/logback") public String logj(){ log.error("我是error"); log.warn("我是warn"); log.info("我是info"); log.debug("我是debug"); return "success"; } /** * logback動態修改包名的日誌級別 * @param level 日誌級別 * @param packageName 包名 * @return * @throws Exception */ @RequestMapping(value = "/level") public String updateLogbackLevel( @RequestParam(value="level") String level, @RequestParam(value="packageName",defaultValue = "-1") String packageName) throws Exception { ch.qos.logback.classic.LoggerContext loggerContext =(ch.qos.logback.classic.LoggerContext) LoggerFactory.getILoggerFactory(); if(packageName.equals("-1")) { // 默認值-1,更改全局日誌級別;不然按傳遞的包名或類名修改日誌級別。 loggerContext.getLogger("root").setLevel(ch.qos.logback.classic.Level.toLevel(level)); } else { loggerContext.getLogger(packageName).setLevel(ch.qos.logback.classic.Level.valueOf(level)); } return "success"; } }
直接調用app
"/level" 接口便可修改日誌級別。