logback-config: added support for FileAppender and TimeBasedRollingPolicy 22/2222/2
authorMilos Fabian <milfabia@cisco.com>
Mon, 28 Oct 2013 13:47:37 +0000 (14:47 +0100)
committerGerrit Code Review <gerrit@opendaylight.org>
Wed, 30 Oct 2013 03:30:34 +0000 (03:30 +0000)
Change-Id: I7cc8b1a6fca10a988dea42dfd7331fe252caf870
Signed-off-by: Milos Fabian <milfabia@cisco.com>
opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/ContextSetterImpl.java
opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/LogbackModule.java
opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleFactory.java
opendaylight/config/logback-config/src/main/java/org/opendaylight/controller/config/yang/logback/config/LogbackStatusListener.java
opendaylight/config/logback-config/src/main/yang/config-logging.yang
opendaylight/config/logback-config/src/test/java/org/opendaylight/controller/config/yang/logback/config/ContextSetterImplTest.java
opendaylight/config/logback-config/src/test/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleTest.java
opendaylight/config/logback-config/src/test/java/org/opendaylight/controller/config/yang/logback/config/LogbackModuleWithInitialConfigurationTest.java
opendaylight/config/logback-config/src/test/java/org/opendaylight/controller/config/yang/logback/config/LogbackWithXmlConfigModuleTest.java
opendaylight/config/logback-config/src/test/resources/simple_config_logback.xml

index 7e4095f..fa8c7f1 100644 (file)
@@ -23,6 +23,7 @@ import ch.qos.logback.classic.spi.ILoggingEvent;
 import ch.qos.logback.core.Appender;
 import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
 import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
+import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
@@ -35,32 +36,25 @@ import com.google.common.collect.Sets;
 public class ContextSetterImpl implements ContextSetter, Closeable {
 
     private final LogbackStatusListener statusListener;
-    private static final org.slf4j.Logger classLogger = LoggerFactory
-            .getLogger(ContextSetterImpl.class);
+    private static final org.slf4j.Logger classLogger = LoggerFactory.getLogger(ContextSetterImpl.class);
 
-    public ContextSetterImpl(
-            LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
-        statusListener = new LogbackStatusListener(
-                rootRuntimeBeanRegistratorWrapper);
+    public ContextSetterImpl(LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
+        statusListener = new LogbackStatusListener(rootRuntimeBeanRegistratorWrapper);
         statusListener.register();
     }
 
     public void updateContext(LogbackModule module) {
-        LoggerContext context = (LoggerContext) LoggerFactory
-                .getILoggerFactory();
+        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
 
-        List<ch.qos.logback.classic.Logger> loggersBefore = context
-                .getLoggerList();
+        List<ch.qos.logback.classic.Logger> loggersBefore = context.getLoggerList();
 
         createLoggers(context, module, Sets.newHashSet(loggersBefore));
     }
 
-    private Map<String, Appender<ILoggingEvent>> createConsoleAppenders(
-            LoggerContext context, LogbackModule module) {
+    private Map<String, Appender<ILoggingEvent>> createConsoleAppenders(LoggerContext context, LogbackModule module) {
         Map<String, Appender<ILoggingEvent>> appendersMap = new HashMap<>();
         for (ConsoleAppenderTO appender : module.getConsoleAppenderTO()) {
-            Preconditions.checkState(
-                    appendersMap.containsKey(appender.getName()) == false,
+            Preconditions.checkState(appendersMap.containsKey(appender.getName()) == false,
                     "Duplicate appender name %s", appender.getName());
             ch.qos.logback.core.ConsoleAppender app = new ch.qos.logback.core.ConsoleAppender();
             app.setContext(context);
@@ -84,70 +78,53 @@ public class ContextSetterImpl implements ContextSetter, Closeable {
     private void createLoggers(LoggerContext context, LogbackModule module,
             Set<ch.qos.logback.classic.Logger> loggersBefore) {
 
-        Map<String, Appender<ILoggingEvent>> appendersMap = getAppenders(
-                module, context);
+        Map<String, Appender<ILoggingEvent>> appendersMap = getAppenders(module, context);
 
         for (LoggerTO logger : module.getLoggerTO()) {
-            classLogger.trace("Setting configuration for logger {}",
-                    logger.getLoggerName());
-            final ch.qos.logback.classic.Logger logbackLogger = context
-                    .getLogger(logger.getLoggerName());
-
-            Optional<Set<Appender<ILoggingEvent>>> appendersBefore = getAppendersBefore(
-                    loggersBefore, logbackLogger);
-            classLogger.trace("Logger {}: Appenders registered before: {}",
-                    logger.getLoggerName(),
-                    appendersBefore.isPresent() ? appendersBefore.get()
-                            : "NO APPENDERS BEFORE");
+            classLogger.trace("Setting configuration for logger {}", logger.getLoggerName());
+            final ch.qos.logback.classic.Logger logbackLogger = context.getLogger(logger.getLoggerName());
+
+            Optional<Set<Appender<ILoggingEvent>>> appendersBefore = getAppendersBefore(loggersBefore, logbackLogger);
+            classLogger.trace("Logger {}: Appenders registered before: {}", logger.getLoggerName(),
+                    appendersBefore.isPresent() ? appendersBefore.get() : "NO APPENDERS BEFORE");
 
             logbackLogger.setLevel(Level.toLevel(logger.getLevel()));
 
-            addNewAppenders(appendersMap, logger, logbackLogger,
-                    appendersBefore);
-            removeBeforeAppenders(loggersBefore, logger, logbackLogger,
-                    appendersBefore);
+            addNewAppenders(appendersMap, logger, logbackLogger, appendersBefore);
+            removeBeforeAppenders(loggersBefore, logger, logbackLogger, appendersBefore);
         }
     }
 
-    private void addNewAppenders(
-            Map<String, Appender<ILoggingEvent>> appendersMap, LoggerTO logger,
-            ch.qos.logback.classic.Logger logbackLogger,
-            Optional<Set<Appender<ILoggingEvent>>> appendersBefore) {
+    private void addNewAppenders(Map<String, Appender<ILoggingEvent>> appendersMap, LoggerTO logger,
+            ch.qos.logback.classic.Logger logbackLogger, Optional<Set<Appender<ILoggingEvent>>> appendersBefore) {
         for (String appenderName : logger.getAppenders()) {
             if (appendersMap.containsKey(appenderName)) {
                 logbackLogger.addAppender(appendersMap.get(appenderName));
-                classLogger.trace("Logger {}: Adding new appender: {}",
-                        logger.getLoggerName(), appenderName);
+                classLogger.trace("Logger {}: Adding new appender: {}", logger.getLoggerName(), appenderName);
             } else {
-                throw new IllegalStateException(
-                        "No appender "
-                                + appenderName
-                                + " found. This error should have been discovered by validation");
+                throw new IllegalStateException("No appender " + appenderName
+                        + " found. This error should have been discovered by validation");
             }
         }
     }
 
-    private void removeBeforeAppenders(
-            Set<ch.qos.logback.classic.Logger> loggersBefore, LoggerTO logger,
-            ch.qos.logback.classic.Logger logbackLogger,
-            Optional<Set<Appender<ILoggingEvent>>> appendersBefore) {
+    private void removeBeforeAppenders(Set<ch.qos.logback.classic.Logger> loggersBefore, LoggerTO logger,
+            ch.qos.logback.classic.Logger logbackLogger, Optional<Set<Appender<ILoggingEvent>>> appendersBefore) {
         if (appendersBefore.isPresent()) {
             for (Appender<ILoggingEvent> appenderBefore : appendersBefore.get()) {
                 logbackLogger.detachAppender(appenderBefore);
                 appenderBefore.stop();
-                classLogger.trace("Logger {}: Removing old appender: {}",
-                        logger.getLoggerName(), appenderBefore.getName());
+                classLogger.trace("Logger {}: Removing old appender: {}", logger.getLoggerName(),
+                        appenderBefore.getName());
             }
             loggersBefore.remove(logbackLogger);
         }
     }
 
-    private Optional<Set<Appender<ILoggingEvent>>> getAppendersBefore(
-            Set<ch.qos.logback.classic.Logger> loggersBefore,
+    private Optional<Set<Appender<ILoggingEvent>>> getAppendersBefore(Set<ch.qos.logback.classic.Logger> loggersBefore,
             ch.qos.logback.classic.Logger logbackLogger) {
         if (loggersBefore.contains(logbackLogger)) {
-            Iterator<Appender<ILoggingEvent>> appenderIt = logbackLogger
-                    .iteratorForAppenders();
+            Iterator<Appender<ILoggingEvent>> appenderIt = logbackLogger.iteratorForAppenders();
             Set<Appender<ILoggingEvent>> appendersBefore = Sets.newHashSet();
             while (appenderIt.hasNext()) {
                 appendersBefore.add(appenderIt.next());
@@ -158,32 +135,50 @@ public class ContextSetterImpl implements ContextSetter, Closeable {
 
     }
 
-    private Map<String, Appender<ILoggingEvent>> getAppenders(
-            LogbackModule module, LoggerContext context) {
+    private Map<String, Appender<ILoggingEvent>> getAppenders(LogbackModule module, LoggerContext context) {
         Map<String, Appender<ILoggingEvent>> appendersMap = new HashMap<>();
         addAllAppenders(appendersMap, createRollingAppenders(context, module));
+        addAllAppenders(appendersMap, createFileAppenders(context, module));
         addAllAppenders(appendersMap, createConsoleAppenders(context, module));
 
         return appendersMap;
     }
 
-    private void addAllAppenders(
-            Map<String, Appender<ILoggingEvent>> allAppenders,
+    private void addAllAppenders(Map<String, Appender<ILoggingEvent>> allAppenders,
             Map<String, Appender<ILoggingEvent>> appendersToAdd) {
         for (String appenderName : appendersToAdd.keySet()) {
-            Preconditions.checkState(
-                    allAppenders.containsKey(appenderName) == false,
-                    "Duplicate appender name %s", appenderName);
+            Preconditions.checkState(allAppenders.containsKey(appenderName) == false, "Duplicate appender name %s",
+                    appenderName);
             allAppenders.put(appenderName, appendersToAdd.get(appenderName));
         }
     }
 
-    private Map<String, Appender<ILoggingEvent>> createRollingAppenders(
-            LoggerContext context, LogbackModule module) {
+    private Map<String, Appender<ILoggingEvent>> createFileAppenders(LoggerContext context, LogbackModule module) {
+        Map<String, Appender<ILoggingEvent>> appendersMap = new HashMap<>();
+        for (FileAppenderTO appender : module.getFileAppenderTO()) {
+            Preconditions.checkState(appendersMap.containsKey(appender.getName()) == false,
+                    "Duplicate appender name %s", appender.getName());
+            ch.qos.logback.core.FileAppender app = new ch.qos.logback.core.FileAppender<>();
+            app.setAppend(appender.getAppend());
+            app.setContext(context);
+            PatternLayoutEncoder encoder = new PatternLayoutEncoder();
+            encoder.setContext(context);
+            encoder.setPattern(appender.getEncoderPattern());
+            encoder.start();
+            app.setEncoder(encoder);
+            app.setFile(appender.getFileName());
+            app.setName(appender.getName());
+            app.start();
+            appendersMap.put(app.getName(), app);
+        }
+
+        return appendersMap;
+    }
+
+    private Map<String, Appender<ILoggingEvent>> createRollingAppenders(LoggerContext context, LogbackModule module) {
         Map<String, Appender<ILoggingEvent>> appendersMap = new HashMap<>();
         for (RollingFileAppenderTO appender : module.getRollingFileAppenderTO()) {
-            Preconditions.checkState(
-                    appendersMap.containsKey(appender.getName()) == false,
+            Preconditions.checkState(appendersMap.containsKey(appender.getName()) == false,
                     "Duplicate appender name %s", appender.getName());
             ch.qos.logback.core.rolling.RollingFileAppender app = new ch.qos.logback.core.rolling.RollingFileAppender<>();
             app.setAppend(appender.getAppend());
@@ -194,14 +189,27 @@ public class ContextSetterImpl implements ContextSetter, Closeable {
             encoder.start();
             app.setEncoder(encoder);
             app.setFile(appender.getFileName());
-            FixedWindowRollingPolicy policy = new FixedWindowRollingPolicy();
-            policy.setContext(context);
-            policy.setMaxIndex(appender.getMaxIndex());
-            policy.setMinIndex(appender.getMinIndex());
-            policy.setFileNamePattern(appender.getFileNamePattern());
-            policy.setParent(app);
-            policy.start();
-            app.setRollingPolicy(policy);
+            if (appender.getRollingPolicyType().equals("FixedWindowRollingPolicy")) {
+                FixedWindowRollingPolicy policy = new FixedWindowRollingPolicy();
+                policy.setContext(context);
+                policy.setMaxIndex(appender.getMaxIndex());
+                policy.setMinIndex(appender.getMinIndex());
+                policy.setFileNamePattern(appender.getFileNamePattern());
+                policy.setParent(app);
+                policy.start();
+                app.setRollingPolicy(policy);
+            } else if (appender.getRollingPolicyType().equals("TimeBasedRollingPolicy")) {
+                TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy();
+                policy.setContext(context);
+                policy.setMaxHistory(appender.getMaxHistory());
+                if (appender.getCleanHistoryOnStart() != null) {
+                    policy.setCleanHistoryOnStart(appender.getCleanHistoryOnStart());
+                }
+                policy.setFileNamePattern(appender.getFileNamePattern());
+                policy.setParent(app);
+                policy.start();
+                app.setRollingPolicy(policy);
+            }
             SizeBasedTriggeringPolicy triggeringPolicy = new SizeBasedTriggeringPolicy();
             triggeringPolicy.setContext(context);
             triggeringPolicy.setMaxFileSize(appender.getMaxFileSize());
index 09c3cb8..faa19be 100644 (file)
@@ -19,18 +19,14 @@ import com.google.common.collect.Sets;
 /**
 *
 */
-public final class LogbackModule
-        extends
-        org.opendaylight.controller.config.yang.logback.config.AbstractLogbackModule {
+public final class LogbackModule extends org.opendaylight.controller.config.yang.logback.config.AbstractLogbackModule {
 
-    public LogbackModule(
-            org.opendaylight.controller.config.api.ModuleIdentifier name,
+    public LogbackModule(org.opendaylight.controller.config.api.ModuleIdentifier name,
             org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(name, dependencyResolver);
     }
 
-    public LogbackModule(
-            org.opendaylight.controller.config.api.ModuleIdentifier name,
+    public LogbackModule(org.opendaylight.controller.config.api.ModuleIdentifier name,
             org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
             org.opendaylight.controller.config.yang.logback.config.AbstractLogbackModule oldModule,
             java.lang.AutoCloseable oldInstance) {
@@ -43,37 +39,27 @@ public final class LogbackModule
         Set<String> appenderNames = Sets.newHashSet();
         validateRollingObjects(appenderNames);
         validateConsoleObjects(appenderNames);
+        validateFileObjects(appenderNames);
         validateLoggersObjects(appenderNames);
     }
 
     private void validateLoggersObjects(Set<String> appenderNames) {
-        JmxAttributeValidationException.checkNotNull(getLoggerTO(),
-                loggersJmxAttribute);
+        JmxAttributeValidationException.checkNotNull(getLoggerTO(), loggersJmxAttribute);
 
         for (LoggerTO loggerToValidate : getLoggerTO()) {
-            JmxAttributeValidationException.checkNotNull(
-                    loggerToValidate.getLoggerName(), "LoggerName is null",
+            JmxAttributeValidationException.checkNotNull(loggerToValidate.getLoggerName(), "LoggerName is null",
                     loggersJmxAttribute);
-            JmxAttributeValidationException.checkNotNull(
-                    loggerToValidate.getLevel(), "Level is null",
-                    loggersJmxAttribute);
-            JmxAttributeValidationException.checkCondition(!loggerToValidate
-                    .getLoggerName().isEmpty(), "LoggerName needs to be set",
-                    loggersJmxAttribute);
-            JmxAttributeValidationException.checkCondition(!loggerToValidate
-                    .getLevel().isEmpty(), "Level needs to be set",
+            JmxAttributeValidationException.checkNotNull(loggerToValidate.getLevel(), "Level is null",
                     loggersJmxAttribute);
+            JmxAttributeValidationException.checkCondition(!loggerToValidate.getLoggerName().isEmpty(),
+                    "LoggerName needs to be set", loggersJmxAttribute);
+            JmxAttributeValidationException.checkCondition(!loggerToValidate.getLevel().isEmpty(),
+                    "Level needs to be set", loggersJmxAttribute);
 
             for (String appenderName : loggerToValidate.getAppenders()) {
-                JmxAttributeValidationException
-                        .checkCondition(
-                                appenderNames.contains(appenderName),
-                                "Appender "
-                                        + appenderName
-                                        + " referenced by logger "
-                                        + loggerToValidate.getLoggerName()
-                                        + " not present in configuration, present appenders: "
-                                        + appenderNames, loggersJmxAttribute);
+                JmxAttributeValidationException.checkCondition(appenderNames.contains(appenderName), "Appender "
+                        + appenderName + " referenced by logger " + loggerToValidate.getLoggerName()
+                        + " not present in configuration, present appenders: " + appenderNames, loggersJmxAttribute);
             }
 
         }
@@ -81,70 +67,91 @@ public final class LogbackModule
 
     private void validateConsoleObjects(Set<String> appenderNames) {
 
-        JmxAttributeValidationException.checkNotNull(getConsoleAppenderTO(),
-                consoleAppendersJmxAttribute);
+        JmxAttributeValidationException.checkNotNull(getConsoleAppenderTO(), consoleAppendersJmxAttribute);
         for (ConsoleAppenderTO object : getConsoleAppenderTO()) {
-            JmxAttributeValidationException.checkNotNull(
-                    object.getEncoderPattern(), "EncoderPattern is null",
+            JmxAttributeValidationException.checkNotNull(object.getEncoderPattern(), "EncoderPattern is null",
                     consoleAppendersJmxAttribute);
 
-            validateAppenderName(appenderNames, object.getName(),
-                    consoleAppendersJmxAttribute);
+            validateAppenderName(appenderNames, object.getName(), consoleAppendersJmxAttribute);
 
-            JmxAttributeValidationException.checkNotNull(
-                    object.getThresholdFilter(), "Filterlevel is null",
+            JmxAttributeValidationException.checkNotNull(object.getThresholdFilter(), "Filterlevel is null",
                     consoleAppendersJmxAttribute);
         }
     }
 
+    private void validateFileObjects(Set<String> appenderNames) {
+        JmxAttributeValidationException.checkNotNull(getFileAppenderTO(), fileAppendersJmxAttribute);
+        for (FileAppenderTO object : getFileAppenderTO()) {
+            JmxAttributeValidationException.checkNotNull(object.getEncoderPattern(), "EncoderPattern is null",
+                    fileAppendersJmxAttribute);
+
+            validateAppenderName(appenderNames, object.getName(), fileAppendersJmxAttribute);
+
+            JmxAttributeValidationException.checkNotNull(object.getFileName(), "FileName is null",
+                    fileAppendersJmxAttribute);
+            JmxAttributeValidationException.checkCondition(!object.getEncoderPattern().isEmpty(),
+                    "EncoderPattern needs to be set", fileAppendersJmxAttribute);
+            JmxAttributeValidationException.checkCondition(!object.getFileName().isEmpty(), "FileName needs to be set",
+                    fileAppendersJmxAttribute);
+
+        }
+    }
+
     private void validateRollingObjects(Set<String> appenderNames) {
 
-        JmxAttributeValidationException.checkNotNull(getRollingFileAppenderTO(),
-                rollingAppendersJmxAttribute);
+        JmxAttributeValidationException.checkNotNull(getRollingFileAppenderTO(), rollingAppendersJmxAttribute);
         for (RollingFileAppenderTO object : getRollingFileAppenderTO()) {
-            JmxAttributeValidationException.checkNotNull(
-                    object.getEncoderPattern(), "EncoderPattern is null",
+            JmxAttributeValidationException.checkNotNull(object.getEncoderPattern(), "EncoderPattern is null",
                     rollingAppendersJmxAttribute);
 
-            validateAppenderName(appenderNames, object.getName(),
+            validateAppenderName(appenderNames, object.getName(), rollingAppendersJmxAttribute);
+
+            JmxAttributeValidationException.checkNotNull(object.getFileName(), "FileName is null",
                     rollingAppendersJmxAttribute);
 
-            JmxAttributeValidationException.checkNotNull(object.getFileName(),
-                    "FileName is null", rollingAppendersJmxAttribute);
-            JmxAttributeValidationException.checkNotNull(
-                    object.getMaxFileSize(), "MaxFileSize is null",
+            JmxAttributeValidationException.checkNotNull(object.getFileNamePattern(), "FileNamePattern is null",
+                    rollingAppendersJmxAttribute);
+            JmxAttributeValidationException.checkNotNull(object.getRollingPolicyType(), "RollingPolicyType is null",
                     rollingAppendersJmxAttribute);
-            JmxAttributeValidationException.checkNotNull(object.getMinIndex(),
-                    "MinIndex is null", rollingAppendersJmxAttribute);
-            JmxAttributeValidationException.checkNotNull(object.getMaxIndex(),
-                    "MaxIndex is null", rollingAppendersJmxAttribute);
-            JmxAttributeValidationException.checkCondition(!object
-                    .getEncoderPattern().isEmpty(),
-                    "EncoderPattern needs to be set",
+            JmxAttributeValidationException.checkCondition(!object.getFileNamePattern().isEmpty(),
+                    "FileNamePattern is not set", rollingAppendersJmxAttribute);
+            JmxAttributeValidationException.checkCondition(!object.getRollingPolicyType().isEmpty(),
+                    "RollingPolicyType is not set", rollingAppendersJmxAttribute);
+            JmxAttributeValidationException.checkCondition(
+                    (object.getRollingPolicyType().equals("FixedWindowRollingPolicy") || object.getRollingPolicyType()
+                            .equals("TimeBasedRollingPolicy")), object.getRollingPolicyType()
+                            + " RollingPolicyType is not supported", rollingAppendersJmxAttribute);
+
+            if (object.getRollingPolicyType().equals("FixedWindowRollingPolicy")) {
+                JmxAttributeValidationException.checkNotNull(object.getMinIndex(), "MinIndex is null",
+                        rollingAppendersJmxAttribute);
+                JmxAttributeValidationException.checkNotNull(object.getMaxIndex(), "MaxIndex is null",
+                        rollingAppendersJmxAttribute);
+            } else if (object.getRollingPolicyType().equals("TimeBasedRollingPolicy")) {
+                JmxAttributeValidationException.checkNotNull(object.getMaxHistory(), "MaxHistory is null",
+                        rollingAppendersJmxAttribute);
+            }
+            JmxAttributeValidationException.checkNotNull(object.getMaxFileSize(), "MaxFileSize is null",
                     rollingAppendersJmxAttribute);
-            JmxAttributeValidationException.checkCondition(!object
-                    .getFileName().isEmpty(), "FileName needs to be set",
+            JmxAttributeValidationException.checkCondition(!object.getEncoderPattern().isEmpty(),
+                    "EncoderPattern needs to be set", rollingAppendersJmxAttribute);
+            JmxAttributeValidationException.checkCondition(!object.getFileName().isEmpty(), "FileName needs to be set",
                     rollingAppendersJmxAttribute);
 
         }
     }
 
-    private void validateAppenderName(Set<String> appenderNames,
-            String appenderName, JmxAttribute jmxAttribute) {
-        JmxAttributeValidationException.checkNotNull(appenderName,
-                "Name is null", jmxAttribute);
-        JmxAttributeValidationException.checkCondition(
-                appenderNames.contains(appenderName) == false,
+    private void validateAppenderName(Set<String> appenderNames, String appenderName, JmxAttribute jmxAttribute) {
+        JmxAttributeValidationException.checkNotNull(appenderName, "Name is null", jmxAttribute);
+        JmxAttributeValidationException.checkCondition(appenderNames.contains(appenderName) == false,
                 "Duplicate appender name " + appenderName, jmxAttribute);
         appenderNames.add(appenderName);
-        JmxAttributeValidationException.checkCondition(!appenderName.isEmpty(),
-                "Name needs to be set", jmxAttribute);
+        JmxAttributeValidationException.checkCondition(!appenderName.isEmpty(), "Name needs to be set", jmxAttribute);
     }
 
     @Override
     public java.lang.AutoCloseable createInstance() {
-        ContextSetterImpl setter = new ContextSetterImpl(
-                getRootRuntimeBeanRegistratorWrapper());
+        ContextSetterImpl setter = new ContextSetterImpl(getRootRuntimeBeanRegistratorWrapper());
 
         setter.updateContext(this);
 
index eb0c7da..732161d 100644 (file)
@@ -24,6 +24,7 @@ import ch.qos.logback.classic.spi.LoggerComparator;
 import ch.qos.logback.core.Appender;
 import ch.qos.logback.core.rolling.FixedWindowRollingPolicy;
 import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
+import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
@@ -31,24 +32,23 @@ import com.google.common.collect.Lists;
 /**
 *
 */
-public class LogbackModuleFactory
-        extends
+public class LogbackModuleFactory extends
         org.opendaylight.controller.config.yang.logback.config.AbstractLogbackModuleFactory {
 
     private static final String INSTANCE_NAME = "singleton";
     private Map<String, LoggerTO> loggersDTOs;
     private Map<String, RollingFileAppenderTO> rollingDTOs;
     private Map<String, ConsoleAppenderTO> consoleDTOs;
+    private Map<String, FileAppenderTO> fileDTOs;
 
     @Override
-    public LogbackModule instantiateModule(String instanceName,
-            DependencyResolver dependencyResolver) {
+    public LogbackModule instantiateModule(String instanceName, DependencyResolver dependencyResolver) {
         Preconditions.checkArgument(instanceName.equals(INSTANCE_NAME),
-                "There should be just one instance of logback, named "
-                        + INSTANCE_NAME);
+                "There should be just one instance of logback, named " + INSTANCE_NAME);
         prepareDTOs();
-        LogbackModule module = new LogbackModule(new ModuleIdentifier(
-                getImplementationName(), INSTANCE_NAME), dependencyResolver);
+        LogbackModule module = new LogbackModule(new ModuleIdentifier(getImplementationName(), INSTANCE_NAME),
+                dependencyResolver);
+        module.setFileAppenderTO(Lists.newArrayList(fileDTOs.values()));
         module.setConsoleAppenderTO(Lists.newArrayList(consoleDTOs.values()));
         module.setRollingFileAppenderTO(Lists.newArrayList(rollingDTOs.values()));
         module.setLoggerTO(Lists.newArrayList(loggersDTOs.values()));
@@ -56,28 +56,25 @@ public class LogbackModuleFactory
     }
 
     @Override
-    public LogbackModule instantiateModule(String instanceName,
-            DependencyResolver dependencyResolver, LogbackModule oldModule,
-            AutoCloseable oldInstance) {
+    public LogbackModule instantiateModule(String instanceName, DependencyResolver dependencyResolver,
+            LogbackModule oldModule, AutoCloseable oldInstance) {
         Preconditions.checkArgument(instanceName.equals(INSTANCE_NAME),
-                "There should be just one instance of logback, named "
-                        + INSTANCE_NAME);
+                "There should be just one instance of logback, named " + INSTANCE_NAME);
         prepareDTOs();
-        LogbackModule module = new LogbackModule(new ModuleIdentifier(
-                getImplementationName(), INSTANCE_NAME), dependencyResolver,
-                oldModule, oldInstance);
+        LogbackModule module = new LogbackModule(new ModuleIdentifier(getImplementationName(), INSTANCE_NAME),
+                dependencyResolver, oldModule, oldInstance);
         module.setConsoleAppenderTO(Lists.newArrayList(consoleDTOs.values()));
         /*
          * module.setJCloudsAppender(Lists.newArrayList(jcloudsDTOs.values()));
          */
+        module.setFileAppenderTO(Lists.newArrayList(fileDTOs.values()));
         module.setRollingFileAppenderTO(Lists.newArrayList(rollingDTOs.values()));
         module.setLoggerTO(Lists.newArrayList(loggersDTOs.values()));
         return module;
     }
 
     private void prepareDTOs() {
-        LoggerContext context = (LoggerContext) LoggerFactory
-                .getILoggerFactory();
+        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
         this.loggersDTOs = prepareLoggersDTOs(context);
         prepareAppendersDTOs(context);
     }
@@ -85,8 +82,10 @@ public class LogbackModuleFactory
     private void prepareAppendersDTOs(LoggerContext context) {
         this.rollingDTOs = new HashMap<>();
         this.consoleDTOs = new HashMap<>();
+        this.fileDTOs = new HashMap<>();
         ch.qos.logback.core.rolling.RollingFileAppender<ILoggingEvent> rollingApp;
         ch.qos.logback.core.ConsoleAppender<ILoggingEvent> consoleApp;
+        ch.qos.logback.core.FileAppender<ILoggingEvent> fileApp;
         Map<Logger, List<Appender<ILoggingEvent>>> appendersAll = new HashMap<>();
         for (Logger log : context.getLoggerList()) {
             List<Appender<ILoggingEvent>> appenders = new ArrayList<>();
@@ -101,45 +100,58 @@ public class LogbackModuleFactory
             for (ch.qos.logback.core.Appender<ILoggingEvent> appender : appEntry) {
                 if (appender instanceof ch.qos.logback.core.rolling.RollingFileAppender<?>) {
                     RollingFileAppenderTO app = new RollingFileAppenderTO();
-                    rollingApp = (ch.qos.logback.core.rolling.RollingFileAppender< ILoggingEvent >) appender;
+                    rollingApp = (ch.qos.logback.core.rolling.RollingFileAppender<ILoggingEvent>) appender;
                     app.setAppend(rollingApp.isAppend());
-                    PatternLayoutEncoder encoder = (PatternLayoutEncoder) rollingApp
-                            .getEncoder();
+                    PatternLayoutEncoder encoder = (PatternLayoutEncoder) rollingApp.getEncoder();
                     app.setEncoderPattern(encoder.getPattern());
                     app.setFileName(rollingApp.getFile());
-                    FixedWindowRollingPolicy rollingPolicy = (FixedWindowRollingPolicy) rollingApp
-                            .getRollingPolicy();
-                    app.setMaxIndex(rollingPolicy.getMaxIndex());
-                    app.setMinIndex(rollingPolicy.getMinIndex());
+                    if (rollingApp.getRollingPolicy() instanceof FixedWindowRollingPolicy) {
+                        FixedWindowRollingPolicy rollingPolicy = (FixedWindowRollingPolicy) rollingApp
+                                .getRollingPolicy();
+                        app.setMaxIndex(rollingPolicy.getMaxIndex());
+                        app.setMinIndex(rollingPolicy.getMinIndex());
+                        app.setFileNamePattern(rollingPolicy.getFileNamePattern());
+                        app.setRollingPolicyType("FixedWindowRollingPolicy");
+                    } else if (rollingApp.getRollingPolicy() instanceof TimeBasedRollingPolicy<?>) {
+                        TimeBasedRollingPolicy rollingPolicy = (TimeBasedRollingPolicy) rollingApp.getRollingPolicy();
+                        app.setRollingPolicyType("TimeBasedRollingPolicy");
+                        app.setFileNamePattern(rollingPolicy.getFileNamePattern());
+                        app.setMaxHistory(rollingPolicy.getMaxHistory());
+                        app.setCleanHistoryOnStart(rollingPolicy.isCleanHistoryOnStart());
+                    }
                     SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = (SizeBasedTriggeringPolicy<ILoggingEvent>) rollingApp
                             .getTriggeringPolicy();
                     app.setMaxFileSize(triggeringPolicy.getMaxFileSize());
-                    app.setFileNamePattern(rollingPolicy.getFileNamePattern());
                     app.setName(rollingApp.getName());
                     this.rollingDTOs.put(rollingApp.getName(), app);
+                } else if (appender instanceof ch.qos.logback.core.FileAppender<?>) {
+                    FileAppenderTO app = new FileAppenderTO();
+                    fileApp = (ch.qos.logback.core.FileAppender<ILoggingEvent>) appender;
+                    app.setName(fileApp.getName());
+                    app.setAppend(fileApp.isAppend());
+                    app.setFileName(fileApp.getFile());
+                    PatternLayoutEncoder encoder = (PatternLayoutEncoder) fileApp.getEncoder();
+                    app.setEncoderPattern(encoder.getPattern());
+                    this.fileDTOs.put(fileApp.getName(), app);
                 }
                 if (appender instanceof ch.qos.logback.core.ConsoleAppender<?>) {
                     ConsoleAppenderTO app = new ConsoleAppenderTO();
                     consoleApp = (ch.qos.logback.core.ConsoleAppender<ILoggingEvent>) appender;
                     consoleApp.getCopyOfAttachedFiltersList();
-                    PatternLayoutEncoder encoder = (PatternLayoutEncoder) consoleApp
-                            .getEncoder();
+                    PatternLayoutEncoder encoder = (PatternLayoutEncoder) consoleApp.getEncoder();
                     app.setEncoderPattern(encoder.getPattern());
                     app.setName(consoleApp.getName());
-                    app.setThresholdFilter(context.getLogger(
-                            Logger.ROOT_LOGGER_NAME).getEffectiveLevel().levelStr);
+                    app.setThresholdFilter(context.getLogger(Logger.ROOT_LOGGER_NAME).getEffectiveLevel().levelStr);
                     this.consoleDTOs.put(consoleApp.getName(), app);
                 }
             }
         }
     }
 
-    private Map<String, LoggerTO> prepareLoggersDTOs(
-            LoggerContext context) {
+    private Map<String, LoggerTO> prepareLoggersDTOs(LoggerContext context) {
         Map<String, LoggerTO> DTOs = new HashMap<>();
         List<String> appenders = new ArrayList<>();
-        List<org.slf4j.Logger> loggersToBeAdd = removeUnusableLoggers(
-                context.getLoggerList(),
+        List<org.slf4j.Logger> loggersToBeAdd = removeUnusableLoggers(context.getLoggerList(),
                 context.getLogger(Logger.ROOT_LOGGER_NAME));
         for (org.slf4j.Logger log : loggersToBeAdd) {
             LoggerTO logger = new LoggerTO();
@@ -148,8 +160,7 @@ public class LogbackModuleFactory
             else
                 logger.setLevel(((Logger) log).getEffectiveLevel().levelStr);
             logger.setLoggerName(log.getName());
-            Iterator<Appender<ILoggingEvent>> iter = ((Logger) log)
-                    .iteratorForAppenders();
+            Iterator<Appender<ILoggingEvent>> iter = ((Logger) log).iteratorForAppenders();
             while (iter.hasNext()) {
                 Appender<ILoggingEvent> element = iter.next();
                 appenders.add(element.getName());
@@ -162,42 +173,35 @@ public class LogbackModuleFactory
         return DTOs;
     }
 
-    private List<org.slf4j.Logger> removeUnusableLoggers(
-            List<Logger> loggerList, Logger rootLogger) {
+    private List<org.slf4j.Logger> removeUnusableLoggers(List<Logger> loggerList, Logger rootLogger) {
         Collections.sort(loggerList, new LoggerComparator());
         Map<String, org.slf4j.Logger> loggersToReturn = new HashMap<>();
 
         for (org.slf4j.Logger log : loggerList) {
             boolean shouldAdd = true;
-            for (Entry<String, org.slf4j.Logger> entry : loggersToReturn
-                    .entrySet()) {
+            for (Entry<String, org.slf4j.Logger> entry : loggersToReturn.entrySet()) {
                 if (StringUtils.contains(log.getName(), entry.getKey())) {
                     if (((Logger) log).getLevel() != null
-                            && ((Logger) log).getLevel().equals(
-                                    ((Logger) entry.getValue()).getLevel())
+                            && ((Logger) log).getLevel().equals(((Logger) entry.getValue()).getLevel())
                             && !((Logger) log).iteratorForAppenders().hasNext()) {
                         shouldAdd = false;
                         break;
                     }
                     if (((Logger) log).getLevel() == null
                             && ((Logger) log).getEffectiveLevel().equals(
-                                    ((Logger) entry.getValue())
-                                            .getEffectiveLevel())
+                                    ((Logger) entry.getValue()).getEffectiveLevel())
                             && !((Logger) log).iteratorForAppenders().hasNext()) {
                         shouldAdd = false;
                         break;
                     }
                 }
-                if (((Logger) log).getLevel() != null
-                        && ((Logger) log).getLevel().equals(
-                                rootLogger.getLevel())
+                if (((Logger) log).getLevel() != null && ((Logger) log).getLevel().equals(rootLogger.getLevel())
                         && !((Logger) log).iteratorForAppenders().hasNext()) {
                     shouldAdd = false;
                     break;
                 }
                 if (((Logger) log).getLevel() == null
-                        && ((Logger) log).getEffectiveLevel().equals(
-                                rootLogger.getEffectiveLevel())
+                        && ((Logger) log).getEffectiveLevel().equals(rootLogger.getEffectiveLevel())
                         && !((Logger) log).iteratorForAppenders().hasNext()) {
                     shouldAdd = false;
                     break;
index dc26779..ca85783 100644 (file)
@@ -23,15 +23,13 @@ import ch.qos.logback.core.status.StatusBase;
 import ch.qos.logback.core.status.StatusListener;
 import ch.qos.logback.core.status.StatusManager;
 
-public class LogbackStatusListener implements StatusListener,
-        LogbackRuntimeMXBean, Closeable {
+public class LogbackStatusListener implements StatusListener, LogbackRuntimeMXBean, Closeable {
 
     private final List<StatusTO> receivedStatuses;
     private final LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper;
     private LogbackRuntimeRegistration reg;
 
-    public LogbackStatusListener(
-            LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
+    public LogbackStatusListener(LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
         receivedStatuses = new ArrayList<>();
         this.rootRuntimeBeanRegistratorWrapper = rootRuntimeBeanRegistratorWrapper;
     }
@@ -52,14 +50,12 @@ public class LogbackStatusListener implements StatusListener,
         return reg;
     }
 
-    private LogbackRuntimeRegistration registerToJMX(
-            LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
+    private LogbackRuntimeRegistration registerToJMX(LogbackRuntimeRegistrator rootRuntimeBeanRegistratorWrapper) {
         return rootRuntimeBeanRegistratorWrapper.register(this);
     }
 
     private synchronized void registerToLogback() {
-        LoggerContext context = (LoggerContext) LoggerFactory
-                .getILoggerFactory();
+        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
         final StatusManager statusManager = context.getStatusManager();
 
         statusManager.remove(this);
@@ -70,15 +66,13 @@ public class LogbackStatusListener implements StatusListener,
     }
 
     private void addInitialStatuses(StatusManager statusManager) {
-        for (ch.qos.logback.core.status.Status status : statusManager
-                .getCopyOfStatusList()) {
+        for (ch.qos.logback.core.status.Status status : statusManager.getCopyOfStatusList()) {
             addStatusEvent(status);
         }
     }
 
     @Override
-    public synchronized void addStatusEvent(
-            ch.qos.logback.core.status.Status status) {
+    public synchronized void addStatusEvent(ch.qos.logback.core.status.Status status) {
         receivedStatuses.add(transformStatus(status));
     }
 
@@ -113,8 +107,7 @@ public class LogbackStatusListener implements StatusListener,
     }
 
     private void unregisterFromLogback() {
-        LoggerContext context = (LoggerContext) LoggerFactory
-                .getILoggerFactory();
+        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
         final StatusManager statusManager = context.getStatusManager();
         statusManager.remove(this);
     }
index d0307f6..7f4ea39 100644 (file)
@@ -31,6 +31,29 @@ module config-logging {
         case logback {
             when "/config:modules/config:module/config:type = 'logback'";
 
+            list file-appenders {
+               leaf append {
+                    type boolean;
+                    mandatory false;
+                }
+
+                leaf file-name {
+                    type string;
+                    mandatory true;
+                }
+                
+                leaf encoder-pattern {
+                    type string;
+                    mandatory true;
+                }
+                
+                leaf name {
+                    type string;
+                    mandatory true;
+                }
+                config:java-name-prefix FileAppenderTO;
+            }
+            
             list rolling-appenders {
                 leaf append {
                     type boolean;
@@ -71,7 +94,21 @@ module config-logging {
                     type string;
                     mandatory true;
                 }
-
+                
+                leaf rolling-policy-type {
+                    type string;
+                    mandatory true;
+                }
+                
+                leaf max-history {
+                    type int32;
+                    mandatory true;
+                }
+                
+                leaf clean-history-on-start {
+                    type boolean;
+                    default 0;
+                }
                 config:java-name-prefix RollingFileAppenderTO;
             }
 
index 7ba7a24..4ba4a02 100644 (file)
@@ -44,8 +44,7 @@ public class ContextSetterImplTest {
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
         LogbackRuntimeRegistration reg = mock(LogbackRuntimeRegistration.class);
-        doReturn(reg).when(runtimeRegistratorMock).register(
-                any(LogbackRuntimeMXBean.class));
+        doReturn(reg).when(runtimeRegistratorMock).register(any(LogbackRuntimeMXBean.class));
     }
 
     @Test
@@ -97,8 +96,7 @@ public class ContextSetterImplTest {
         List<ConsoleAppenderTO> consoleAppenders = Lists.newArrayList();
 
         for (String loggerName : loggersToAppenders.keySet()) {
-            LoggerTO l1 = createLogger(loggerName,
-                    loggersToAppenders.get(loggerName));
+            LoggerTO l1 = createLogger(loggerName, loggersToAppenders.get(loggerName));
             logger.add(l1);
             for (String appenderName : loggersToAppenders.get(loggerName)) {
                 consoleAppenders.add(createConsoleAppender(appenderName));
@@ -106,14 +104,12 @@ public class ContextSetterImplTest {
 
         }
 
-        LogbackModule logbackModule = createLogbackModule(logger,
-                consoleAppenders);
+        LogbackModule logbackModule = createLogbackModule(logger, consoleAppenders);
         setter.updateContext(logbackModule);
     }
 
     private void assertLoggerWithAppenders(String name, String... appenders) {
-        LoggerContext context = (LoggerContext) LoggerFactory
-                .getILoggerFactory();
+        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
         ch.qos.logback.classic.Logger logger = context.getLogger(name);
         Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders();
 
@@ -129,22 +125,18 @@ public class ContextSetterImplTest {
 
         for (String appender : appenders) {
             boolean isPresent = foundAppenders.get(appender).isEmpty();
-            assertFalse(
-                    "Appender " + appender + " for logger " + name
-                            + " was not present, present appenders: "
-                            + foundAppenders.keys(), isPresent);
+            assertFalse("Appender " + appender + " for logger " + name + " was not present, present appenders: "
+                    + foundAppenders.keys(), isPresent);
         }
 
     }
 
-    private LogbackModule createLogbackModule(List<LoggerTO> logger,
-            List<ConsoleAppenderTO> consoleAppenders) {
-        LogbackModule logbackModule = new LogbackModule(new ModuleIdentifier(
-                "fact", "first"), dependencyResolverMock);
+    private LogbackModule createLogbackModule(List<LoggerTO> logger, List<ConsoleAppenderTO> consoleAppenders) {
+        LogbackModule logbackModule = new LogbackModule(new ModuleIdentifier("fact", "first"), dependencyResolverMock);
         logbackModule.setLoggerTO(logger);
         logbackModule.setConsoleAppenderTO(consoleAppenders);
-        logbackModule.setRollingFileAppenderTO(Lists
-                .<RollingFileAppenderTO> newArrayList());
+        logbackModule.setRollingFileAppenderTO(Lists.<RollingFileAppenderTO> newArrayList());
+        logbackModule.setFileAppenderTO(Lists.<FileAppenderTO> newArrayList());
         return logbackModule;
     }
 
index 1e2327e..846b9cd 100644 (file)
@@ -37,22 +37,18 @@ public class LogbackModuleTest extends AbstractConfigTest {
     private LogbackModuleFactory factory;
 
     @Before
-    public void setUp() throws IOException, ClassNotFoundException,
-            InterruptedException {
+    public void setUp() throws IOException, ClassNotFoundException, InterruptedException {
 
         factory = new LogbackModuleFactory();
-        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(
-                factory));
+        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(factory));
     }
 
     @Test
     public void testCreateBean() throws InstanceAlreadyExistsException {
 
-        CommitStatus status = createBeans(
-        true, "target/rollingApp",
-                "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB",
-                1, 5, "target/%i.log", "rolling", "consoleName", "ALL",
-                "logger1", "DEBUG").commit();
+        CommitStatus status = createBeans(true, "target/rollingApp",
+                "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1, 5, "target/%i.log", "rolling",
+                "consoleName", "ALL", "logger1", "DEBUG", "FixedWindowRollingPolicy", 0, "FileAppender").commit();
 
         assertBeanCount(1, factory.getImplementationName());
         assertStatus(status, 1, 0, 0);
@@ -60,16 +56,13 @@ public class LogbackModuleTest extends AbstractConfigTest {
 
     @Test
     public void testReusingInstance() throws InstanceAlreadyExistsException {
-        createBeans(
-        true, "target/rollingApp",
-                "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB",
-                1, 5, "target/%i.log", "rolling", "consoleName", "ALL",
-                "logger1", "DEBUG").commit();
+        createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1, 5,
+                "target/%i.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG", "FixedWindowRollingPolicy", 0,
+                "FileAppender").commit();
 
         assertBeanCount(1, factory.getImplementationName());
 
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
         CommitStatus status = transaction.commit();
 
         assertBeanCount(1, factory.getImplementationName());
@@ -77,23 +70,17 @@ public class LogbackModuleTest extends AbstractConfigTest {
     }
 
     @Test
-    public void testRecreateInstance() throws InstanceAlreadyExistsException,
-            ValidationException, ConflictingVersionException,
-            InstanceNotFoundException {
-        createBeans(
-        true, "target/rollingApp",
-                "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB",
-                1, 5, "target/%i.log", "rolling", "consoleName", "ALL",
-                "logger1", "DEBUG").commit();
+    public void testRecreateInstance() throws InstanceAlreadyExistsException, ValidationException,
+            ConflictingVersionException, InstanceNotFoundException {
+        createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1, 5,
+                "target/%i.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG", "FixedWindowRollingPolicy", 0,
+                "FileAppender").commit();
 
         assertBeanCount(1, LogbackModuleFactory.NAME);
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
 
-        ObjectName logback = transaction.lookupConfigBean(
-                LogbackModuleFactory.NAME, "singleton");
-        LogbackModuleMXBean nwBean = transaction.newMXBeanProxy(logback,
-                LogbackModuleMXBean.class);
+        ObjectName logback = transaction.lookupConfigBean(LogbackModuleFactory.NAME, "singleton");
+        LogbackModuleMXBean nwBean = transaction.newMXBeanProxy(logback, LogbackModuleMXBean.class);
         CommitStatus status = transaction.commit();
         assertBeanCount(1, LogbackModuleFactory.NAME);
 
@@ -101,19 +88,14 @@ public class LogbackModuleTest extends AbstractConfigTest {
     }
 
     @Test
-    public void testDestroyInstance() throws InstanceNotFoundException,
-            InstanceAlreadyExistsException {
-        createBeans(
-        true, "target/rollingApp",
-                "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB",
-                1, 5, "target/%i.log", "rolling", "consoleName", "ALL",
-                "logger1", "DEBUG").commit();
+    public void testDestroyInstance() throws InstanceNotFoundException, InstanceAlreadyExistsException {
+        createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1, 5,
+                "target/%i.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG", "FixedWindowRollingPolicy", 0,
+                "FileAppender").commit();
         assertBeanCount(1, factory.getImplementationName());
 
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
-        transaction.destroyConfigBean(factory.getImplementationName(),
-                INSTANCE_NAME);
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        transaction.destroyConfigBean(factory.getImplementationName(), INSTANCE_NAME);
         CommitStatus status = transaction.commit();
 
         assertBeanCount(0, factory.getImplementationName());
@@ -124,58 +106,47 @@ public class LogbackModuleTest extends AbstractConfigTest {
     @Test
     public void testValidation1() throws InstanceAlreadyExistsException {
         try {
-            createBeans(
-            true, "target/rollingApp",
-                    "%-4relative [%thread] %-5level %logger{35} - %msg%n",
-                    "30MB", 1, 5, "target/%i.log", "rolling", "consoleName",
-                    "ALL", "logger1", "DEBUG").commit();
+            createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1, 5,
+                    "target/%i.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG", "FixedWindowRollingPolicy",
+                    0, "FileAppender").commit();
             fail();
         } catch (ValidationException e) {
-            assertThat(e.getFailedValidations().toString(),
-                    containsString("FileName is null"));
+            assertThat(e.getFailedValidations().toString(), containsString("FileName is null"));
         }
     }
 
     @Test
     public void testValidation2() throws InstanceAlreadyExistsException {
         try {
-            createBeans(
-            true, "target/rollingApp", null, "30MB", 1, 5, "target/%i.log",
-                    "rolling", "consoleName", "ALL", "logger1", "DEBUG")
-                    .commit();
+            createBeans(true, "target/rollingApp", null, "30MB", 1, 5, "target/%i.log", "rolling", "consoleName",
+                    "ALL", "logger1", "DEBUG", "FixedWindowRollingPolicy", 0, "FileAppender").commit();
             fail();
         } catch (ValidationException e) {
-            assertThat(e.getFailedValidations().toString(),
-                    containsString("EncoderPattern is null"));
+            assertThat(e.getFailedValidations().toString(), containsString("EncoderPattern is null"));
         }
     }
 
     @Test
     public void testValidation4() throws InstanceAlreadyExistsException {
         try {
-            createBeans(
-            true, "target/rollingApp",
-                    "%-4relative [%thread] %-5level %logger{35} - %msg%n",
-                    null, 1, 5, "target/%i.log", "rolling", "consoleName",
-                    "ALL", "logger1", "DEBUG").commit();
+            createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", null, 1, 5,
+                    "target/%i.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG", "FixedWindowRollingPolicy",
+                    0, "FileAppender").commit();
             fail();
         } catch (ValidationException e) {
-            assertThat(e.getFailedValidations().toString(),
-                    containsString("MaxFileSize is null"));
+            assertThat(e.getFailedValidations().toString(), containsString("MaxFileSize is null"));
         }
     }
 
     @Test
     public void testValidation6() throws InstanceAlreadyExistsException {
         try {
-            createBeans(
-            true, "", "%-4relative [%thread] %-5level %logger{35} - %msg%n",
-                    "30MB", 1, 5, "target/%i.log", "rolling", "consoleName",
-                    "ALL", "logger1", "DEBUG").commit();
+            createBeans(true, "", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1, 5, "target/%i.log",
+                    "rolling", "consoleName", "ALL", "logger1", "DEBUG", "FixedWindowRollingPolicy", 0, "FileAppender")
+                    .commit();
             fail();
         } catch (ValidationException e) {
-            assertThat(e.getFailedValidations().toString(),
-                    containsString("FileName needs to be set"));
+            assertThat(e.getFailedValidations().toString(), containsString("FileName needs to be set"));
         }
     }
 
@@ -184,88 +155,112 @@ public class LogbackModuleTest extends AbstractConfigTest {
         try {
             createBeans(
 
-            true, "target/rollingApp", "", "30MB", 1, 5, "target/%i.log",
-                    "rolling", "consoleName", "ALL", "logger1", "DEBUG")
-                    .commit();
+            true, "target/rollingApp", "", "30MB", 1, 5, "target/%i.log", "rolling", "consoleName", "ALL", "logger1",
+                    "DEBUG", "FixedWindowRollingPolicy", 0, "FileAppender").commit();
             fail();
         } catch (ValidationException e) {
-            assertThat(e.getFailedValidations().toString(),
-                    containsString("EncoderPattern needs to be set"));
+            assertThat(e.getFailedValidations().toString(), containsString("EncoderPattern needs to be set"));
         }
     }
 
     @Test
     public void testValidation8() throws InstanceAlreadyExistsException {
         try {
-            createBeans(
-            true, "target/rollingApp",
-                    "%-4relative [%thread] %-5level %logger{35} - %msg%n",
-                    "30MB", 1, 5, "target/%i.log", "rolling", "consoleName",
-                    "ALL", null, "DEBUG").commit();
+            createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1, 5,
+                    "target/%i.log", "rolling", "consoleName", "ALL", null, "DEBUG", "FixedWindowRollingPolicy", 0,
+                    "FileAppender").commit();
             fail();
         } catch (ValidationException e) {
-            assertThat(e.getFailedValidations().toString(),
-                    containsString("LoggerName is null"));
+            assertThat(e.getFailedValidations().toString(), containsString("LoggerName is null"));
         }
     }
 
     @Test
     public void testValidation9() throws InstanceAlreadyExistsException {
         try {
-            createBeans(
-            true, "target/rollingApp",
-                    "%-4relative [%thread] %-5level %logger{35} - %msg%n",
-                    "30MB", 1, 5, "target/%i.log", "rolling", "consoleName",
-                    "ALL", "", "DEBUG").commit();
+            createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1, 5,
+                    "target/%i.log", "rolling", "consoleName", "ALL", "", "DEBUG", "FixedWindowRollingPolicy", 0,
+                    "FileAppender").commit();
             fail();
         } catch (ValidationException e) {
-            assertThat(e.getFailedValidations().toString(),
-                    containsString("LoggerName needs to be set"));
+            assertThat(e.getFailedValidations().toString(), containsString("LoggerName needs to be set"));
         }
     }
 
     @Test
     public void testValidation10() throws InstanceAlreadyExistsException {
         try {
-            createBeans(
-            true, "target/rollingApp",
-                    "%-4relative [%thread] %-5level %logger{35} - %msg%n",
-                    "30MB", null, 5, "target/%i.log", "rolling", "consoleName",
-                    "ALL", "logger1", "DEBUG").commit();
+            createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", null,
+                    5, "target/%i.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG",
+                    "FixedWindowRollingPolicy", 0, "FileAppender").commit();
             fail();
         } catch (ValidationException e) {
-            assertThat(e.getFailedValidations().toString(),
-                    containsString("MinIndex is null"));
+            assertThat(e.getFailedValidations().toString(), containsString("MinIndex is null"));
         }
     }
 
     @Test
     public void testValidation11() throws InstanceAlreadyExistsException {
         try {
-            createBeans(
-            true, "target/rollingApp",
-                    "%-4relative [%thread] %-5level %logger{35} - %msg%n",
-                    "30MB", 1, null, "target/%i.log", "rolling", "consoleName",
-                    "ALL", "logger1", "DEBUG").commit();
+            createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1,
+                    null, "target/%i.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG",
+                    "FixedWindowRollingPolicy", 0, "FileAppender").commit();
+            fail();
+        } catch (ValidationException e) {
+            assertThat(e.getFailedValidations().toString(), containsString("MaxIndex is null"));
+        }
+    }
+
+    @Test
+    public void testValidation12() throws InstanceAlreadyExistsException {
+        try {
+            createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1,
+                    null, "target/%i.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG", null, 1, "FileAppender")
+                    .commit();
             fail();
         } catch (ValidationException e) {
-            assertThat(e.getFailedValidations().toString(),
-                    containsString("MaxIndex is null"));
+            assertThat(e.getFailedValidations().toString(), containsString("RollingPolicyType is null"));
         }
     }
 
-    private ConfigTransactionJMXClient createBeans(
-    Boolean isAppend, String rollingFileName, String encoderPattern,
-            String maxFileSize, Integer minIndex, Integer maxIndex,
-            String fileNamePattern, String rollingName, String consoleName,
-            String thresholdFilter, String loggerName, String level )
-            throws InstanceAlreadyExistsException {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
-        ObjectName nameCreated = transaction.createModule(
-                factory.getImplementationName(), INSTANCE_NAME);
-        LogbackModuleMXBean bean = transaction.newMXBeanProxy(nameCreated,
-                LogbackModuleMXBean.class);
+    @Test
+    public void testValidation13() throws InstanceAlreadyExistsException {
+        try {
+            createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1,
+                    null, "target/%i.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG", "", 1, "FileAppender")
+                    .commit();
+            fail();
+        } catch (ValidationException e) {
+            assertThat(e.getFailedValidations().toString(), containsString("RollingPolicyType is not set"));
+        }
+    }
+
+    @Test
+    public void testValidation14() throws InstanceAlreadyExistsException {
+        try {
+            createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", 1,
+                    null, "target/%i.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG", "RollingPolicy", 1,
+                    "FileAppender").commit();
+            fail();
+        } catch (ValidationException e) {
+            assertThat(e.getFailedValidations().toString(), containsString("RollingPolicyType is not supported"));
+        }
+    }
+
+    @Test
+    public void testTimeBasedRollingPolicy() throws InstanceAlreadyExistsException {
+        createBeans(true, "target/rollingApp", "%-4relative [%thread] %-5level %logger{35} - %msg%n", "30MB", null,
+                null, "target/%d.log", "rolling", "consoleName", "ALL", "logger1", "DEBUG", "TimeBasedRollingPolicy",
+                1, "FileAppender").commit();
+    }
+
+    private ConfigTransactionJMXClient createBeans(Boolean isAppend, String rollingFileName, String encoderPattern,
+            String maxFileSize, Integer minIndex, Integer maxIndex, String fileNamePattern, String rollingName,
+            String consoleName, String thresholdFilter, String loggerName, String level, String rollingPolicyType,
+            int maxHistory, String fileAppName) throws InstanceAlreadyExistsException {
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        ObjectName nameCreated = transaction.createModule(factory.getImplementationName(), INSTANCE_NAME);
+        LogbackModuleMXBean bean = transaction.newMXBeanProxy(nameCreated, LogbackModuleMXBean.class);
 
         List<RollingFileAppenderTO> rollingAppenders = new ArrayList<>();
         RollingFileAppenderTO rollingAppender = new RollingFileAppenderTO();
@@ -277,6 +272,8 @@ public class LogbackModuleTest extends AbstractConfigTest {
         rollingAppender.setMinIndex(minIndex);
         rollingAppender.setFileNamePattern(fileNamePattern);
         rollingAppender.setName(rollingName);
+        rollingAppender.setRollingPolicyType(rollingPolicyType);
+        rollingAppender.setMaxHistory(maxHistory);
         rollingAppenders.add(rollingAppender);
 
         List<ConsoleAppenderTO> consoleAppenders = new ArrayList<>();
@@ -286,6 +283,14 @@ public class LogbackModuleTest extends AbstractConfigTest {
         consoleAppender.setThresholdFilter(thresholdFilter);
         consoleAppenders.add(consoleAppender);
 
+        List<FileAppenderTO> fileAppenders = new ArrayList<>();
+        FileAppenderTO fileAppender = new FileAppenderTO();
+        fileAppender.setName(fileAppName);
+        fileAppender.setAppend(isAppend);
+        fileAppender.setEncoderPattern(encoderPattern);
+        fileAppender.setFileName(rollingFileName);
+        fileAppenders.add(fileAppender);
+
         List<LoggerTO> loggers = new ArrayList<>();
 
         LoggerTO logger = new LoggerTO();
@@ -298,6 +303,7 @@ public class LogbackModuleTest extends AbstractConfigTest {
         bean.setLoggerTO(loggers);
         bean.setRollingFileAppenderTO(rollingAppenders);
         bean.setConsoleAppenderTO(consoleAppenders);
+        bean.setFileAppenderTO(fileAppenders);
 
         transaction.validateConfig();
 
index 2bdfa47..79e46ae 100644 (file)
@@ -40,8 +40,7 @@ import ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy;
 
 import com.google.common.collect.Lists;
 
-public class LogbackModuleWithInitialConfigurationTest extends
-        AbstractConfigTest {
+public class LogbackModuleWithInitialConfigurationTest extends AbstractConfigTest {
 
     private LogbackModuleFactory factory;
 
@@ -49,36 +48,32 @@ public class LogbackModuleWithInitialConfigurationTest extends
     public void setUp() throws IOException, ClassNotFoundException {
 
         factory = new LogbackModuleFactory();
-        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(
-                factory));
+        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(factory));
     }
 
     /**
      * Tests that initial configuration was changed. Changed attributes:
-     * location, fileName, duplicateInsertTries
-     *
+     * location, fileName, duplicateInsertTries. Added new FileAppender.
      */
     @Test
     public void test() throws Exception {
 
         createBeans();
 
-        ConfigTransactionClient transaction = configRegistryClient
-                .createTransaction();
+        ConfigTransactionClient transaction = configRegistryClient.createTransaction();
 
-        LogbackModuleMXBean bean = JMX.newMXBeanProxy(
-                ManagementFactory.getPlatformMBeanServer(),
-                transaction.lookupConfigBean("logback", "singleton"),
-                LogbackModuleMXBean.class);
+        LogbackModuleMXBean bean = JMX.newMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
+                transaction.lookupConfigBean("logback", "singleton"), LogbackModuleMXBean.class);
         assertEquals(1, bean.getConsoleAppenderTO().size());
         assertEquals(1, bean.getRollingFileAppenderTO().size());
+        assertEquals(0, bean.getFileAppenderTO().size());
         assertEquals(1, bean.getLoggerTO().size());
 
         RollingFileAppenderTO rolling = new RollingFileAppenderTO();
-        RollingFileAppenderTO old = bean
-                .getRollingFileAppenderTO().get(0);
+        RollingFileAppenderTO old = bean.getRollingFileAppenderTO().get(0);
         rolling.setAppend(old.getAppend());
         rolling.setEncoderPattern(old.getEncoderPattern());
+        rolling.setRollingPolicyType(old.getRollingPolicyType());
         rolling.setFileName("target/logFile1.log");
         rolling.setFileNamePattern("target/%i.log");
         rolling.setMaxFileSize(old.getMaxFileSize());
@@ -91,56 +86,69 @@ public class LogbackModuleWithInitialConfigurationTest extends
         console.setName("SYSTEM");
         console.setThresholdFilter("DEBUG");
 
+        FileAppenderTO file = new FileAppenderTO();
+        file.setName("FILE_APPENDER");
+        file.setAppend(true);
+        file.setEncoderPattern("%-4relative [%thread] %-5level %logger{35} - %msg%n");
+        file.setFileName("target/testFile.log");
+
         bean.setConsoleAppenderTO(Lists.newArrayList(console));
         bean.setRollingFileAppenderTO(Lists.newArrayList(rolling));
+        bean.setFileAppenderTO(Lists.newArrayList(file));
 
         LoggerTO logger = new LoggerTO();
         logger.setLevel("INFO");
         logger.setLoggerName("logger");
         logger.setAppenders(Lists.newArrayList("SYSTEM"));
-        List<LoggerTO> loggers = Lists
-                .newArrayList(logger);
+
+        LoggerTO fileLogger = new LoggerTO();
+        fileLogger.setLevel("DEBUG");
+        fileLogger.setLoggerName("fileLogger");
+        fileLogger.setAppenders(Lists.newArrayList("FILE_APPENDER"));
+
+        List<LoggerTO> loggers = Lists.newArrayList(logger, fileLogger);
         bean.setLoggerTO(loggers);
 
         transaction.commit();
 
         LogbackModuleMXBean logback = configRegistryClient.newMXBeanProxy(
-                ObjectNameUtil.createReadOnlyModuleON("logback", "singleton"),
-                LogbackModuleMXBean.class);
-
+                ObjectNameUtil.createReadOnlyModuleON("logback", "singleton"), LogbackModuleMXBean.class);
 
-        List<RollingFileAppenderTO> rollingList = logback
-                .getRollingFileAppenderTO();
+        List<RollingFileAppenderTO> rollingList = logback.getRollingFileAppenderTO();
         assertEquals(1, rollingList.size());
 
-        RollingFileAppenderTO rollingApp = rollingList
-                .get(0);
+        RollingFileAppenderTO rollingApp = rollingList.get(0);
         assertEquals(rollingApp.getFileName(), "target/logFile1.log");
         assertEquals(rollingApp.getName(), "FILE");
 
-        List<ConsoleAppenderTO> consoleList = logback
-                .getConsoleAppenderTO();
+        List<ConsoleAppenderTO> consoleList = logback.getConsoleAppenderTO();
         assertEquals(1, consoleList.size());
 
-        ConsoleAppenderTO consoleApp = consoleList
-                .get(0);
+        ConsoleAppenderTO consoleApp = consoleList.get(0);
         assertEquals(consoleApp.getThresholdFilter(), "DEBUG");
         assertEquals(consoleApp.getName(), "SYSTEM");
 
+        List<FileAppenderTO> fileList = logback.getFileAppenderTO();
+        assertEquals(1, fileList.size());
+
+        FileAppenderTO fileApp = fileList.get(0);
+        assertEquals(fileApp.getFileName(), "target/testFile.log");
+        assertEquals(fileApp.getName(), "FILE_APPENDER");
+
         loggers = logback.getLoggerTO();
-        assertEquals(1, loggers.size());
+        assertEquals(2, loggers.size());
+        assertEquals("logger", loggers.get(0).getLoggerName());
+        assertEquals("fileLogger", loggers.get(1).getLoggerName());
 
     }
 
-    public ObjectName createBeans() throws JoranException,
-            InstanceAlreadyExistsException, IOException {
+    public ObjectName createBeans() throws JoranException, InstanceAlreadyExistsException, IOException {
 
         LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
 
         JoranConfigurator configurator = new JoranConfigurator();
         configurator.setContext(lc);
-        configurator
-                .doConfigure("src/test/resources/simple_config_logback.xml");
+        configurator.doConfigure("src/test/resources/simple_config_logback.xml");
         File f = new File("target/it");
         if (f.exists())
             FileUtils.cleanDirectory(f);
@@ -155,12 +163,11 @@ public class LogbackModuleWithInitialConfigurationTest extends
         List<RollingFileAppenderTO> rollingAppenders = new ArrayList<>();
         RollingFileAppenderTO rollingApp = new RollingFileAppenderTO();
         rollingApp.setAppend(fileAppender.isAppend());
-        PatternLayoutEncoder enc = (PatternLayoutEncoder) fileAppender
-                .getEncoder();
+        PatternLayoutEncoder enc = (PatternLayoutEncoder) fileAppender.getEncoder();
         rollingApp.setEncoderPattern(enc.getPattern());
         rollingApp.setFileName(fileAppender.getFile());
-        FixedWindowRollingPolicy rollingPolicy = (FixedWindowRollingPolicy) fileAppender
-                .getRollingPolicy();
+        FixedWindowRollingPolicy rollingPolicy = (FixedWindowRollingPolicy) fileAppender.getRollingPolicy();
+        rollingApp.setRollingPolicyType("FixedWindowRollingPolicy");
         rollingApp.setMaxIndex(rollingPolicy.getMaxIndex());
         rollingApp.setMinIndex(rollingPolicy.getMinIndex());
         SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = (SizeBasedTriggeringPolicy<ILoggingEvent>) fileAppender
@@ -182,25 +189,24 @@ public class LogbackModuleWithInitialConfigurationTest extends
         consoleApp.setThresholdFilter("ALL");
         consoleAppenders.add(consoleApp);
 
+        List<FileAppenderTO> fileAppenders = new ArrayList<>();
+
         List<LoggerTO> loggersDTOs = new ArrayList<>();
         LoggerTO log = new LoggerTO();
-        log.setAppenders(Arrays.asList(fileAppender.getName(),
-                consoleApp.getName()));
+        log.setAppenders(Arrays.asList(fileAppender.getName(), consoleApp.getName()));
 
         log.setLevel(logger.getLevel().toString());
         log.setLoggerName(logger.getName());
         loggersDTOs.add(log);
 
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
-        ObjectName nameCreated = transaction.createModule(
-                factory.getImplementationName(), "singleton");
-        LogbackModuleMXBean bean = transaction.newMXBeanProxy(nameCreated,
-                LogbackModuleMXBean.class);
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        ObjectName nameCreated = transaction.createModule(factory.getImplementationName(), "singleton");
+        LogbackModuleMXBean bean = transaction.newMXBeanProxy(nameCreated, LogbackModuleMXBean.class);
 
         bean.setLoggerTO(loggersDTOs);
         bean.setRollingFileAppenderTO(rollingAppenders);
         bean.setConsoleAppenderTO(consoleAppenders);
+        bean.setFileAppenderTO(fileAppenders);
 
         transaction.commit();
 
index ce3a019..517302b 100644 (file)
@@ -12,6 +12,8 @@ import static org.junit.Assert.assertEquals;
 import java.io.File;
 import java.io.IOException;
 import java.lang.management.ManagementFactory;
+import java.util.ArrayList;
+import java.util.List;
 
 import javax.management.InstanceAlreadyExistsException;
 import javax.management.InstanceNotFoundException;
@@ -26,6 +28,8 @@ import org.opendaylight.controller.config.manager.impl.factoriesresolver.Hardcod
 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.collect.Lists;
+
 import ch.qos.logback.classic.LoggerContext;
 import ch.qos.logback.classic.joran.JoranConfigurator;
 import ch.qos.logback.core.joran.spi.JoranException;
@@ -39,15 +43,13 @@ public class LogbackWithXmlConfigModuleTest extends AbstractConfigTest {
     public void setUp() throws JoranException, IOException {
 
         factory = new LogbackModuleFactory();
-        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(
-                factory));
+        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(factory));
 
         lc = (LoggerContext) LoggerFactory.getILoggerFactory();
         JoranConfigurator configurator = new JoranConfigurator();
         lc.reset();
         configurator.setContext(lc);
-        configurator
-                .doConfigure("src/test/resources/simple_config_logback.xml");
+        configurator.doConfigure("src/test/resources/simple_config_logback.xml");
         File f = new File("target/it");
         if (f.exists())
             FileUtils.cleanDirectory(f);
@@ -57,16 +59,12 @@ public class LogbackWithXmlConfigModuleTest extends AbstractConfigTest {
      * Tests configuration of Logger factory.
      */
     @Test
-    public void test() throws InstanceAlreadyExistsException,
-            InstanceNotFoundException {
+    public void test() throws InstanceAlreadyExistsException, InstanceNotFoundException {
 
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
-        ObjectName nameCreated = transaction.createModule(
-                factory.getImplementationName(), "singleton");
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        ObjectName nameCreated = transaction.createModule(factory.getImplementationName(), "singleton");
 
-        LogbackModuleMXBean bean = transaction.newMXBeanProxy(nameCreated,
-                LogbackModuleMXBean.class);
+        LogbackModuleMXBean bean = transaction.newMXBeanProxy(nameCreated, LogbackModuleMXBean.class);
 
         assertEquals(1, bean.getConsoleAppenderTO().size());
 
@@ -76,11 +74,9 @@ public class LogbackWithXmlConfigModuleTest extends AbstractConfigTest {
 
         transaction = configRegistryClient.createTransaction();
 
-        nameCreated = transaction.lookupConfigBean(
-                factory.getImplementationName(), "singleton");
+        nameCreated = transaction.lookupConfigBean(factory.getImplementationName(), "singleton");
 
-        bean = JMX.newMXBeanProxy(platformMBeanServer, nameCreated,
-                LogbackModuleMXBean.class);
+        bean = JMX.newMXBeanProxy(platformMBeanServer, nameCreated, LogbackModuleMXBean.class);
 
         assertEquals(1, bean.getConsoleAppenderTO().size());
         assertEquals(1, bean.getRollingFileAppenderTO().size());
@@ -92,22 +88,47 @@ public class LogbackWithXmlConfigModuleTest extends AbstractConfigTest {
      * loggers should be removed.
      */
     @Test
-    public void testAllLoggers() throws InstanceAlreadyExistsException,
-            InstanceNotFoundException {
-        ConfigTransactionJMXClient transaction = configRegistryClient
-                .createTransaction();
+    public void testAllLoggers() throws InstanceAlreadyExistsException, InstanceNotFoundException {
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
         transaction.createModule(factory.getImplementationName(), "singleton");
 
         transaction.commit();
 
         transaction = configRegistryClient.createTransaction();
 
-        LogbackModuleMXBean bean = JMX.newMXBeanProxy(
-                ManagementFactory.getPlatformMBeanServer(),
-                transaction.lookupConfigBean("logback", "singleton"),
-                LogbackModuleMXBean.class);
+        LogbackModuleMXBean bean = JMX.newMXBeanProxy(ManagementFactory.getPlatformMBeanServer(),
+                transaction.lookupConfigBean("logback", "singleton"), LogbackModuleMXBean.class);
 
         assertEquals(5, bean.getLoggerTO().size());
     }
 
+    /**
+     * Add new logger using FileAppender
+     */
+    @Test
+    public void testAddNewLogger() throws InstanceAlreadyExistsException, InstanceNotFoundException {
+
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        ObjectName nameCreated = transaction.createModule(factory.getImplementationName(), "singleton");
+        LogbackModuleMXBean bean = transaction.newMXBeanProxy(nameCreated, LogbackModuleMXBean.class);
+
+        assertEquals(5, bean.getLoggerTO().size());
+
+        List<LoggerTO> loggers = Lists.newArrayList(bean.getLoggerTO());
+        LoggerTO logger = new LoggerTO();
+        logger.setAppenders(Lists.newArrayList("FILE"));
+        logger.setLevel("INFO");
+        logger.setLoggerName("fileLogger");
+        loggers.add(logger);
+        bean.setLoggerTO(loggers);
+
+        transaction.commit();
+
+        transaction = configRegistryClient.createTransaction();
+        nameCreated = transaction.lookupConfigBean(factory.getImplementationName(), "singleton");
+        bean = JMX.newMXBeanProxy(platformMBeanServer, nameCreated, LogbackModuleMXBean.class);
+
+        assertEquals(6, bean.getLoggerTO().size());
+    }
+
 }
index f4535de..f00a7f0 100644 (file)
         <encoder>
             <pattern>[%d{HH:mm:ss.SSS}] [%thread] %-5level %logger - %msg%n</pattern>
         </encoder>
-        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
-            <fileNamePattern>/opt/Demo1/logs/bgp.log.%i.gz</fileNamePattern>
-            <minIndex>1</minIndex>
-            <maxIndex>5</maxIndex>
+        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
+            <fileNamePattern>/opt/Demo1/logs/bgp.log.%d{yyyy-MM-dd}.gz</fileNamePattern>
+            <maxHistory>30</maxHistory>
         </rollingPolicy>
 
         <triggeringPolicy
         </triggeringPolicy>
 
     </appender>
-
+    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
+        <file>target/testFile.log</file>
+        <append>true</append>
+        <encoder>
+           <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
+        </encoder>
+    </appender>
 
     <!-- Increase to INFO to see content of REST messages -->
     <logger name="org.apache.cxf.interceptor.LoggingInInterceptor"
@@ -71,6 +76,7 @@
         -->
         <appender-ref ref="STDOUT"/>
         <appender-ref ref="VARLOGFILE"/>
+        <appender-ref ref="FILE"/>
     </root>
 
 </configuration>