Authored by Gino Zhang

支持动态调整日志级别

... ... @@ -16,6 +16,8 @@ import java.util.concurrent.TimeUnit;
*/
public final class LogUtils {
private static final Logger ROOT_LOGGER = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private static final Map<String, Level> sourceLevelMap = new ConcurrentHashMap<>();
// 最大支持打开五分钟
... ... @@ -38,8 +40,8 @@ public final class LogUtils {
return "The logger [" + loggerName + "] is not found.";
}
final Level srcLevel = logger.getLevel();
if (srcLevel == null || level == srcLevel) {
final Level srcLevel = logger.getLevel() != null ? logger.getLevel() : ROOT_LOGGER.getLevel();
if (level == srcLevel) {
return "The logger [" + loggerName + "] is [" + levelStr + "] already.";
}
... ...
... ... @@ -177,11 +177,21 @@ public class ToolsController {
}
/**
* 用于动态地变更日记级别。
* @param loggerName 日志名称,有三类:
* 第一种是ROOT,对所有日志都起作用,
* 第二种是具体的日志名称,如CACHE_MATCH_REQUEST,
* 第三种就是全限定类名,如com.yoho.search.service.servicenew.impl.ProductListServiceImpl。
* @param level 调整目标级别,支持ALL/TRACE/DEBUG/INFO/WARN/ERROR/OFF这些取值
* @param seconds 调整日志级别的有效时间,默认为60秒,最多只能为300秒,到了时间后变更为原来的日志级别。
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/changeLogLevel")
@ResponseBody
public SearchApiResult changeLogLevel(@RequestParam(defaultValue = "ProductListServiceImpl") String loggerName,
@RequestParam(defaultValue = "DEBUG") String level,
@RequestParam(defaultValue = "60") int seconds) throws Exception {
@RequestParam(defaultValue = "60") int seconds) {
try {
return new SearchApiResult().setData(LogUtils.changeRootLogLevel(loggerName, level, seconds));
} catch (Exception e) {
... ...
... ... @@ -21,6 +21,23 @@
</encoder>
</appender>
<!-- DEBUG级别日志 appender -->
<appender name="DEBUG" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器,过滤掉 TRACE 和 DEBUG 和 INFO 级别的日志 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${catalina.home}/logs/%d{yyyy-MM-dd}/debug.log</fileNamePattern>
<!-- 日志最大的保存天数 -->
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>${maxFileSize}</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<!-- WARN级别日志 appender -->
<appender name="WARN" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 过滤器,过滤掉 TRACE 和 DEBUG 和 INFO 级别的日志 -->
... ... @@ -191,6 +208,8 @@
<appender-ref ref="STDOUT" />
<!-- 文件输出 -->
<appender-ref ref="WARN" />
<!-- 文件输出 -->
<appender-ref ref="DEBUG" />
</root>
<!-- http请求处理超时日志 -->
... ...