private void testPatternFormatter(final String profileName) throws Exception {
    final KernelServices kernelServices = boot();
    final String fileHandlerName = "test-file-handler";

    final File logFile = createLogFile();

    // Add file handler
    final ModelNode handlerAddress =
        addFileHandler(
            kernelServices,
            profileName,
            fileHandlerName,
            org.jboss.logmanager.Level.INFO,
            logFile,
            false);

    // Get the logger
    final Logger logger = getLogger(profileName);

    // Create the logger
    final ModelNode loggerAddress =
        createLoggerAddress(profileName, logger.getName()).toModelNode();
    ModelNode op = SubsystemOperations.createAddOperation(loggerAddress);
    op.get(LoggerResourceDefinition.USE_PARENT_HANDLERS.getName()).set(false);
    op.get(CommonAttributes.HANDLERS.getName()).setEmptyList().add(fileHandlerName);
    executeOperation(kernelServices, op);

    // Create a pattern formatter
    final ModelNode patternFormatterAddress =
        createPatternFormatterAddress(profileName, "PATTERN").toModelNode();
    op = SubsystemOperations.createAddOperation(patternFormatterAddress);
    // Add a format that can be read back to make sure it matches the pattern used in the handler
    op.get(PatternFormatterResourceDefinition.PATTERN.getName()).set("[NAMED-PATTERN] %s%n");
    executeOperation(kernelServices, op);

    // Add the named formatter to the handler
    op =
        SubsystemOperations.createWriteAttributeOperation(
            handlerAddress, FileHandlerResourceDefinition.NAMED_FORMATTER, "PATTERN");
    executeOperation(kernelServices, op);

    // Log 3 lines
    logger.info("Test message 1");
    logger.info("Test message 2");
    logger.info("Test message 3");

    // Check the file, should only contain 3 lines
    final List<String> lines = FileUtils.readLines(logFile);
    assertEquals(
        "Additional messages written to handler that should not be there.", 3, lines.size());

    // Check each line
    assertEquals("Line patterns don't match.", "[NAMED-PATTERN] Test message 1", lines.get(0));
    assertEquals("Line patterns don't match.", "[NAMED-PATTERN] Test message 2", lines.get(1));
    assertEquals("Line patterns don't match.", "[NAMED-PATTERN] Test message 3", lines.get(2));

    // Clean up
    op =
        SubsystemOperations.CompositeOperationBuilder.create()
            .addStep(SubsystemOperations.createRemoveOperation(loggerAddress))
            .addStep(SubsystemOperations.createRemoveOperation(handlerAddress))
            .addStep(SubsystemOperations.createRemoveOperation(patternFormatterAddress))
            .build()
            .getOperation();
    executeOperation(kernelServices, op);
  }
  private void testDisableHandler(final String profileName, boolean legacy) throws Exception {
    final KernelServices kernelServices = boot();
    final String fileHandlerName = "test-file-handler";

    final File logFile = createLogFile();

    // Add file handler
    addFileHandler(
        kernelServices,
        profileName,
        fileHandlerName,
        org.jboss.logmanager.Level.INFO,
        logFile,
        true);

    // Ensure the handler is listed
    final ModelNode rootLoggerAddress = createRootLoggerAddress(profileName).toModelNode();
    ModelNode op =
        SubsystemOperations.createReadAttributeOperation(
            rootLoggerAddress, CommonAttributes.HANDLERS);
    ModelNode handlerResult = executeOperation(kernelServices, op);
    List<String> handlerList = SubsystemOperations.readResultAsList(handlerResult);
    assertTrue(
        String.format("Handler '%s' was not found. Result: %s", fileHandlerName, handlerResult),
        handlerList.contains(fileHandlerName));

    // Get the logger
    final Logger logger = getLogger(profileName);

    // Log 3 lines
    logger.info("Test message 1");
    logger.info("Test message 2");
    logger.info("Test message 3");

    // Disable the handler
    final ModelNode handlerAddress =
        createFileHandlerAddress(profileName, fileHandlerName).toModelNode();
    ModelNode disableOp =
        legacy
            ? Util.getEmptyOperation(
                AbstractHandlerDefinition.DISABLE_HANDLER.getName(), handlerAddress)
            : SubsystemOperations.createWriteAttributeOperation(
                handlerAddress, CommonAttributes.ENABLED, false);
    executeOperation(kernelServices, disableOp);

    // The operation should set the enabled attribute to false
    final ModelNode readOp =
        SubsystemOperations.createReadAttributeOperation(handlerAddress, CommonAttributes.ENABLED);
    ModelNode result = executeOperation(kernelServices, readOp);
    assertFalse(
        "enabled attribute should be false when the disable operation is invoked",
        SubsystemOperations.readResult(result).asBoolean());

    // Log 3 more lines
    logger.info("Test message 4");
    logger.info("Test message 5");
    logger.info("Test message 6");

    // Check the file, should only contain 3 lines
    List<String> lines = FileUtils.readLines(logFile);
    assertEquals("Handler was not disable.", 3, lines.size());

    // Re-enable the handler
    ModelNode enableOp =
        legacy
            ? Util.getEmptyOperation(
                AbstractHandlerDefinition.ENABLE_HANDLER.getName(), handlerAddress)
            : SubsystemOperations.createWriteAttributeOperation(
                handlerAddress, CommonAttributes.ENABLED, true);
    executeOperation(kernelServices, enableOp);

    // The operation should set the enabled attribute to true
    result = executeOperation(kernelServices, readOp);
    assertTrue(
        "enabled attribute should be true when the enable operation is invoked",
        SubsystemOperations.readResult(result).asBoolean());

    // Log 3 more lines
    logger.info("Test message 7");
    logger.info("Test message 8");
    logger.info("Test message 9");

    // Check the file, should contain 6 lines
    lines = FileUtils.readLines(logFile);
    assertEquals("Handler was not disable.", 6, lines.size());
  }
  @Test
  public void testLoggingProfile() throws Exception {
    final KernelServices kernelServices = boot();
    final String handlerName = "test-file-handler";

    final File logFile = createLogFile();
    final File profileLogFile = createLogFile("profile.log");
    final ModelNode handlerAddress = createFileHandlerAddress(handlerName).toModelNode();
    final ModelNode profileHandlerAddress =
        createFileHandlerAddress(PROFILE, handlerName).toModelNode();

    // Add handlers
    addFileHandler(
        kernelServices, null, handlerName, org.jboss.logmanager.Level.INFO, logFile, true);
    addFileHandler(
        kernelServices,
        PROFILE,
        handlerName,
        org.jboss.logmanager.Level.INFO,
        profileLogFile,
        true);

    // Change the format
    ModelNode op =
        SubsystemOperations.createReadAttributeOperation(
            handlerAddress, AbstractHandlerDefinition.FORMATTER);
    final String defaultHandlerFormat =
        SubsystemOperations.readResultAsString(executeOperation(kernelServices, op));
    op =
        SubsystemOperations.createReadAttributeOperation(
            profileHandlerAddress, AbstractHandlerDefinition.FORMATTER);
    final String defaultProfileHandlerFormat =
        SubsystemOperations.readResultAsString(executeOperation(kernelServices, op));
    op =
        SubsystemOperations.createWriteAttributeOperation(
            handlerAddress, AbstractHandlerDefinition.FORMATTER, "%m%n");
    executeOperation(kernelServices, op);
    op =
        SubsystemOperations.createWriteAttributeOperation(
            profileHandlerAddress, AbstractHandlerDefinition.FORMATTER, "%m%n");
    executeOperation(kernelServices, op);

    // Log with and without profile
    final String msg = "This is a test message";
    doLog(null, LEVELS, msg);
    doLog(PROFILE, LEVELS, msg);

    // Reset the formatters
    op =
        SubsystemOperations.createWriteAttributeOperation(
            handlerAddress, AbstractHandlerDefinition.FORMATTER, defaultHandlerFormat);
    executeOperation(kernelServices, op);
    op =
        SubsystemOperations.createWriteAttributeOperation(
            profileHandlerAddress,
            AbstractHandlerDefinition.FORMATTER,
            defaultProfileHandlerFormat);
    executeOperation(kernelServices, op);

    // Remove the handler
    removeFileHandler(kernelServices, null, handlerName, true);
    removeFileHandler(kernelServices, PROFILE, handlerName, true);

    // Read the files to a string
    final String result = FileUtils.readFileToString(logFile);
    final String profileResult = FileUtils.readFileToString(profileLogFile);

    // Check generated log file
    assertTrue(result.contains(msg));
    assertTrue(profileResult.contains(msg));

    // The contents of the files should match
    assertTrue(
        String.format(
            "Contents don't match: %nResult:%n%s%nProfileResult%n%s", result, profileResult),
        result.equals(profileResult));
  }
  private void testChangeRootLogLevel(final String loggingProfile) throws Exception {
    final KernelServices kernelServices = boot();
    final String fileHandlerName = "test-file-handler";

    // add new file logger so we can track logged messages
    final File logFile = createLogFile();
    addFileHandler(
        kernelServices,
        loggingProfile,
        fileHandlerName,
        org.jboss.logmanager.Level.TRACE,
        logFile,
        true);

    final Level[] levels = {
      org.jboss.logmanager.Level.FATAL,
      org.jboss.logmanager.Level.ERROR,
      org.jboss.logmanager.Level.WARN,
      org.jboss.logmanager.Level.INFO,
      org.jboss.logmanager.Level.DEBUG,
      org.jboss.logmanager.Level.TRACE
    };
    final Map<Level, Integer> levelOrd = new HashMap<Level, Integer>();
    levelOrd.put(org.jboss.logmanager.Level.FATAL, 0);
    levelOrd.put(org.jboss.logmanager.Level.ERROR, 1);
    levelOrd.put(org.jboss.logmanager.Level.WARN, 2);
    levelOrd.put(org.jboss.logmanager.Level.INFO, 3);
    levelOrd.put(org.jboss.logmanager.Level.DEBUG, 4);
    levelOrd.put(org.jboss.logmanager.Level.TRACE, 5);

    // log messages on all levels with different root logger level settings
    final ModelNode address = createRootLoggerAddress(loggingProfile).toModelNode();
    for (Level level : levels) {
      // change root log level
      final ModelNode op =
          SubsystemOperations.createWriteAttributeOperation(
              address, CommonAttributes.LEVEL, level.getName());
      executeOperation(kernelServices, op);
      doLog(loggingProfile, levels, "RootLoggerTestCaseTST %s", level);
    }

    // Remove the handler
    removeFileHandler(kernelServices, loggingProfile, fileHandlerName, true);

    // go through logged messages - test that with each root logger level settings
    // message with equal priority and also messages with all higher
    // priorities were logged

    final boolean[][] logFound = new boolean[levelOrd.size()][levelOrd.size()];

    final List<String> logLines = FileUtils.readLines(logFile);
    for (String line : logLines) {
      if (!line.contains("RootLoggerTestCaseTST")) continue; // not our log
      final String[] words = line.split("\\s+");
      try {
        final Level lineLogLevel = Level.parse(words[1]);
        final Level rootLogLevel = Level.parse(words[5]);
        final int producedLevel = levelOrd.get(lineLogLevel);
        final int loggedLevel = levelOrd.get(rootLogLevel);
        assertTrue(
            String.format(
                "Produced level(%s) greater than logged level (%s)", lineLogLevel, rootLogLevel),
            producedLevel <= loggedLevel);
        logFound[producedLevel][loggedLevel] = true;
      } catch (Exception e) {
        throw new Exception("Unexpected log:" + line);
      }
    }
    for (Level level : levels) {
      final int rl = levelOrd.get(level);
      for (int ll = 0; ll <= rl; ll++) assertTrue(logFound[ll][rl]);
    }
  }
  @Test
  public void testLegacyFilters() throws Exception {
    final KernelServices kernelServices = boot();
    final String fileHandlerName = "test-file-handler";

    // add new file logger so we can track logged messages
    final File logFile = createLogFile();
    final ModelNode handlerAddress = createFileHandlerAddress(fileHandlerName).toModelNode();
    addFileHandler(
        kernelServices, null, fileHandlerName, org.jboss.logmanager.Level.TRACE, logFile, true);
    // Write legacy filters
    for (Map.Entry<String, ModelNode> entry : FilterConversionTestCase.MAP.entrySet()) {
      // Validate the write-attribute operation
      ModelNode op =
          SubsystemOperations.createWriteAttributeOperation(
              handlerAddress, CommonAttributes.FILTER, entry.getValue());
      executeOperation(kernelServices, op);
      // Read the current value
      op =
          SubsystemOperations.createReadAttributeOperation(
              handlerAddress, CommonAttributes.FILTER_SPEC);
      String filterSpecResult =
          SubsystemOperations.readResultAsString(executeOperation(kernelServices, op));
      assertEquals(entry.getKey(), filterSpecResult);

      // Validate an add operation
      final ModelNode tempHandlerAddress = createConsoleHandlerAddress("temp").toModelNode();
      op = SubsystemOperations.createAddOperation(tempHandlerAddress);
      op.get(CommonAttributes.FILTER.getName()).set(entry.getValue());
      executeOperation(kernelServices, op);
      // Read the current value
      op =
          SubsystemOperations.createReadAttributeOperation(
              tempHandlerAddress, CommonAttributes.FILTER_SPEC);
      filterSpecResult =
          SubsystemOperations.readResultAsString(executeOperation(kernelServices, op));
      assertEquals(entry.getKey(), filterSpecResult);
      // Remove the temp handler
      op = SubsystemOperations.createRemoveOperation(tempHandlerAddress, true);
      executeOperation(kernelServices, op);

      // Add to a logger
      final ModelNode loggerAddress = createLoggerAddress("test-logger").toModelNode();
      op = SubsystemOperations.createAddOperation(loggerAddress);
      op.get(CommonAttributes.FILTER.getName()).set(entry.getValue());
      executeOperation(kernelServices, op);
      // Read the current value
      op =
          SubsystemOperations.createReadAttributeOperation(
              loggerAddress, CommonAttributes.FILTER_SPEC);
      filterSpecResult =
          SubsystemOperations.readResultAsString(executeOperation(kernelServices, op));
      assertEquals(entry.getKey(), filterSpecResult);

      // Remove the attribute
      op =
          SubsystemOperations.createUndefineAttributeOperation(
              loggerAddress, CommonAttributes.FILTER_SPEC);
      executeOperation(kernelServices, op);
      op = SubsystemOperations.createReadAttributeOperation(loggerAddress, CommonAttributes.FILTER);
      // Filter and filter spec should be undefined
      assertEquals(
          "Filter was not undefined",
          SubsystemOperations.UNDEFINED,
          SubsystemOperations.readResult(executeOperation(kernelServices, op)));
      op =
          SubsystemOperations.createReadAttributeOperation(
              loggerAddress, CommonAttributes.FILTER_SPEC);
      assertEquals(
          "Filter was not undefined",
          SubsystemOperations.UNDEFINED,
          SubsystemOperations.readResult(executeOperation(kernelServices, op)));

      // Test writing the attribute to the logger
      op =
          SubsystemOperations.createWriteAttributeOperation(
              loggerAddress, CommonAttributes.FILTER, entry.getValue());
      executeOperation(kernelServices, op);
      // Read the current value
      op =
          SubsystemOperations.createReadAttributeOperation(
              loggerAddress, CommonAttributes.FILTER_SPEC);
      filterSpecResult =
          SubsystemOperations.readResultAsString(executeOperation(kernelServices, op));
      assertEquals(entry.getKey(), filterSpecResult);

      // Remove the logger
      op = SubsystemOperations.createRemoveOperation(loggerAddress, true);
      executeOperation(kernelServices, op);
    }

    // Write new filters
    for (Map.Entry<String, ModelNode> entry : FilterConversionTestCase.MAP.entrySet()) {
      // Write to a handler
      ModelNode op =
          SubsystemOperations.createWriteAttributeOperation(
              handlerAddress, CommonAttributes.FILTER_SPEC, entry.getKey());
      executeOperation(kernelServices, op);
      // Read the current value
      op =
          SubsystemOperations.createReadAttributeOperation(handlerAddress, CommonAttributes.FILTER);
      ModelNode filterResult = SubsystemOperations.readResult(executeOperation(kernelServices, op));
      ModelTestUtils.compare(entry.getValue(), filterResult);

      // Validate an add operation
      final ModelNode tempHandlerAddress = createConsoleHandlerAddress("temp").toModelNode();
      op = SubsystemOperations.createAddOperation(tempHandlerAddress);
      op.get(CommonAttributes.FILTER_SPEC.getName()).set(entry.getKey());
      executeOperation(kernelServices, op);
      // Read the current value
      op =
          SubsystemOperations.createReadAttributeOperation(
              tempHandlerAddress, CommonAttributes.FILTER);
      filterResult = SubsystemOperations.readResult(executeOperation(kernelServices, op));
      ModelTestUtils.compare(entry.getValue(), filterResult);
      // Remove the temp handler
      op = SubsystemOperations.createRemoveOperation(tempHandlerAddress, true);
      executeOperation(kernelServices, op);

      // Add to a logger
      final ModelNode loggerAddress = createLoggerAddress("test-logger").toModelNode();
      op = SubsystemOperations.createAddOperation(loggerAddress);
      op.get(CommonAttributes.FILTER_SPEC.getName()).set(entry.getKey());
      executeOperation(kernelServices, op);
      // Read the current value
      op = SubsystemOperations.createReadAttributeOperation(loggerAddress, CommonAttributes.FILTER);
      filterResult = SubsystemOperations.readResult(executeOperation(kernelServices, op));
      ModelTestUtils.compare(entry.getValue(), filterResult);

      // Test writing the attribute to the logger
      op =
          SubsystemOperations.createWriteAttributeOperation(
              loggerAddress, CommonAttributes.FILTER_SPEC, entry.getKey());
      executeOperation(kernelServices, op);
      // Read the current value
      op = SubsystemOperations.createReadAttributeOperation(loggerAddress, CommonAttributes.FILTER);
      filterResult = SubsystemOperations.readResult(executeOperation(kernelServices, op));
      ModelTestUtils.compare(entry.getValue(), filterResult);

      // Remove the logger
      op = SubsystemOperations.createRemoveOperation(loggerAddress, true);
      executeOperation(kernelServices, op);
    }
    removeFileHandler(kernelServices, null, fileHandlerName, true);
  }