如何在logback

时间:2016-07-26 11:41:45

标签: logback

我的项目中有一个已定义的logback,这是配置:

<?xml version="1.0" encoding="UTF-8"?>

<appender name="DAILY" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>/logApp/application.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>/logApp/application.log.%d{yyyy-MM-dd}.%i.gz</fileNamePattern>
    </rollingPolicy>

    <encoder>
        <charset>UTF-8</charset>
        <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36}:%line - %msg%n</pattern>
    </encoder>
</appender>

<appender name="HOURLY" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>/logApp/application.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>/logApp/application.log.%d{yyyy-MM-dd-HH}.%i.gz</fileNamePattern>
    </rollingPolicy>

    <encoder>
        <charset>UTF-8</charset>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36}:%line - %msg%n</pattern>
    </encoder>
</appender>

<root level="info">
    <appender-ref ref="DAILY" />
</root>

你可以看到我只在我的root配置中使用每日appender。如何在运行时间(HOURLY / DAILY)之间切换这些定义的appender?

我尝试使用以下代码,但我的newAppender始终为null:

String loggingAppender = "HOURLY";
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
ch.qos.logback.classic.Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);
root.detachAndStopAllAppenders();
Appender<ILoggingEvent> newAppender = root.getAppender(loggingAppender);
root.addAppender(newAppender);

0 个答案:

没有答案