org.jboss.logmanager.LogContext Java Examples

The following examples show how to use org.jboss.logmanager.LogContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EnvironmentRestorer.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
synchronized void restoreLogContextSelector() {
    if (!logContextSelectorRestored) {
        final LogContext logContext = defaultContexts.getLogContext();
        if (logContext == LogContext.getSystemLogContext()) {
            LogContext.setLogContextSelector(LogContext.DEFAULT_LOG_CONTEXT_SELECTOR);
        } else {
            LogContext.setLogContextSelector(new LogContextSelector() {
                @Override
                public LogContext getLogContext() {
                    return logContext;
                }
            });
        }
        EmbeddedLogContext.clearLogContext();
        logContextSelectorRestored = true;
    }
}
 
Example #2
Source File: LogContextStdioContextSelector.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public StdioContext getStdioContext() {
    final LogContext logContext = LogContext.getLogContext();
    final Logger root = logContext.getLogger(CommonAttributes.ROOT_LOGGER_NAME);
    StdioContext stdioContext = root.getAttachment(STDIO_CONTEXT_ATTACHMENT_KEY);
    if (stdioContext == null) {
        stdioContext = StdioContext.create(
                new NullInputStream(),
                new LoggingOutputStream(logContext.getLogger("stdout"), Level.INFO),
                new LoggingOutputStream(logContext.getLogger("stderr"), Level.ERROR)
        );
        final StdioContext appearing = root.attachIfAbsent(STDIO_CONTEXT_ATTACHMENT_KEY, stdioContext);
        if (appearing != null) {
            stdioContext = appearing;
        }
    }
    return stdioContext;
}
 
Example #3
Source File: AbstractLoggingDeploymentProcessor.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public final void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    // If the log context is already defined, skip the rest of the processing
    if (!hasRegisteredLogContext(deploymentUnit)) {
        if (deploymentUnit.hasAttachment(Attachments.DEPLOYMENT_ROOT)) {
            // don't process sub-deployments as they are processed by processing methods
            final ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
            if (SubDeploymentMarker.isSubDeployment(root)) return;
            processDeployment(phaseContext, deploymentUnit, root);
            // If we still don't have a context registered on the root deployment, register the current context.
            // This is done to avoid any logging from the root deployment to have access to a sub-deployments log
            // context. For example any library logging from a EAR/lib should use the EAR's configured log context,
            // not a log context from a WAR or EJB library.
            if (!hasRegisteredLogContext(deploymentUnit) && !deploymentUnit.hasAttachment(DEFAULT_LOG_CONTEXT_KEY)) {
                // Register the current log context as this could be an embedded server or overridden another way
                registerLogContext(deploymentUnit, DEFAULT_LOG_CONTEXT_KEY, deploymentUnit.getAttachment(Attachments.MODULE), LogContext.getLogContext());
            }
        }
    }
}
 
Example #4
Source File: AbstractLoggingDeploymentProcessor.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void registerLogContext(final DeploymentUnit deploymentUnit, final AttachmentKey<LogContext> attachmentKey, final Module module, final LogContext logContext) {
    LoggingLogger.ROOT_LOGGER.tracef("Registering LogContext %s for deployment %s", logContext, deploymentUnit.getName());
    if (WildFlySecurityManager.isChecking()) {
        WildFlySecurityManager.doUnchecked(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                logContextSelector.registerLogContext(module.getClassLoader(), logContext);
                return null;
            }
        });
    } else {
        logContextSelector.registerLogContext(module.getClassLoader(), logContext);
    }
    // Add the log context to the sub-deployment unit for later removal
    deploymentUnit.putAttachment(attachmentKey, logContext);
}
 
Example #5
Source File: AbstractLoggingDeploymentProcessor.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void unregisterLogContext(final DeploymentUnit deploymentUnit, final AttachmentKey<LogContext> attachmentKey, final Module module) {
    final LogContext logContext = deploymentUnit.removeAttachment(attachmentKey);
    if (logContext != null) {
        final boolean success;
        if (WildFlySecurityManager.isChecking()) {
            success = WildFlySecurityManager.doUnchecked(new PrivilegedAction<Boolean>() {
                @Override
                public Boolean run() {
                    return logContextSelector.unregisterLogContext(module.getClassLoader(), logContext);
                }
            });
        } else {
            success = logContextSelector.unregisterLogContext(module.getClassLoader(), logContext);
        }
        if (success) {
            LoggingLogger.ROOT_LOGGER.tracef("Removed LogContext '%s' from '%s'", logContext, module);
        } else {
            LoggingLogger.ROOT_LOGGER.logContextNotRemoved(logContext, deploymentUnit.getName());
        }
    }
}
 
Example #6
Source File: WildFlyLogContextSelectorImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public boolean unregisterLogContext(final ClassLoader classLoader, final LogContext logContext) {
    if (contextSelector.unregisterLogContext(classLoader, logContext)) {
        synchronized (this) {
            if (counter > 0) {
                counter--;
            } else if (dftCounter > 0) {
                // We don't test the log context here and just assume we're using the default. This is safe as the
                // registered log contexts must be the default log context.
                dftCounter--;
            }
        }
        return true;
    }
    return false;
}
 
Example #7
Source File: WildFlyLogContextSelectorImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void registerLogContext(final ClassLoader classLoader, final LogContext logContext) {
    // We want to register regardless of the current counter for cases when a different log context is registered
    // later.
    contextSelector.registerLogContext(classLoader, logContext);
    synchronized (this) {
        if (counter > 0) {
            counter++;
        } else if (logContext != defaultLogContextSelector.getLogContext()) {
            // Move the dftCounter to the counter and add one for this specific log context
            counter = dftCounter + 1;
            dftCounter = 0;
        } else {
            // We're using the default log context at this point
            dftCounter++;
        }
    }
}
 
Example #8
Source File: BootableJar.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private LogContext configureLogContext() throws IOException {
    final Path baseDir = jbossHome.resolve(STANDALONE);
    String serverLogDir = System.getProperty(JBOSS_SERVER_LOG_DIR, null);
    if (serverLogDir == null) {
        serverLogDir = baseDir.resolve(LOG).toString();
        System.setProperty(JBOSS_SERVER_LOG_DIR, serverLogDir);
    }
    final String serverCfgDir = System.getProperty(JBOSS_SERVER_CONFIG_DIR, baseDir.resolve(CONFIGURATION).toString());
    final LogContext embeddedLogContext = LogContext.create();
    final Path bootLog = Paths.get(serverLogDir).resolve(SERVER_LOG);
    final Path loggingProperties = Paths.get(serverCfgDir).resolve(Paths.get(LOGGING_PROPERTIES));
    if (Files.exists(loggingProperties)) {
        try (final InputStream in = Files.newInputStream(loggingProperties)) {
            System.setProperty(LOG_BOOT_FILE_PROP, bootLog.toAbsolutePath().toString());
            PropertyConfigurator configurator = new PropertyConfigurator(embeddedLogContext);
            configurator.configure(in);
        }
    }
    return embeddedLogContext;
}
 
Example #9
Source File: LoggingConfigurationFileReloader.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private LoggingConfigurationUpdater getOrCreateUpdater() {
   final LogContext logContext = LogContext.getLogContext();
   final org.jboss.logmanager.Logger rootLogger = logContext.getLogger("");
   LoggingConfigurationUpdater updater = rootLogger.getAttachment(KEY);
   if (updater == null) {
      final LogContextConfiguration logContextConfiguration = getOrCreateConfiguration(rootLogger);
      if (logContextConfiguration == null) {
         return null;
      }
      updater = new LoggingConfigurationUpdater(logContextConfiguration);
      final LoggingConfigurationUpdater appearing = rootLogger.attachIfAbsent(KEY, updater);
      if (appearing != null) {
         updater = appearing;
      }
   }
   return updater;
}
 
Example #10
Source File: LoggingSubsystemTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testConfiguration() throws Exception {
    final KernelServices kernelServices = boot();
    final ModelNode currentModel = getSubsystemModel(kernelServices);
    compare(currentModel, ConfigurationPersistence.getConfigurationPersistence(LogContext.getLogContext()));

    // Compare properties written out to current model
    final String dir = resolveRelativePath(kernelServices, "jboss.server.config.dir");
    Assert.assertNotNull("jboss.server.config.dir could not be resolved", dir);
    final LogContext logContext = LogContext.create();
    final ConfigurationPersistence config = ConfigurationPersistence.getOrCreateConfigurationPersistence(logContext);
    try (final FileInputStream in = new FileInputStream(new File(dir, "logging.properties"))) {
        config.configure(in);
        compare(currentModel, config);
    }

    kernelServices.shutdown();
}
 
Example #11
Source File: ThreadLocalContextSelector.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public LogContext getLogContext() {
    // CLI loggers should only use the default stdio context regardless if the thread-local context is set This
    // allows the context configured for CLI, e.g. jboss-cli-logging.properties.
    final ClassLoader tccl = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();
    if (tccl != null && tccl.equals(cliClassLoader)) {
        return defaultContexts.getLogContext();
    }
    Contexts threadContext = threadLocal.get();
    LogContext local = threadContext != null ? threadContext.getLogContext() : null;
    return local == null ? defaultContexts.getLogContext() : local;
}
 
Example #12
Source File: AbstractLoggingSubsystemTest.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("ChainOfInstanceofChecks")
private LogContextConfiguration getLogContextConfiguration(final LogContext logContext) {
    final Configurator configurator = logContext.getAttachment(CommonAttributes.ROOT_LOGGER_NAME, Configurator.ATTACHMENT_KEY);
    if (configurator instanceof LogContextConfiguration) {
        return (LogContextConfiguration) configurator;
    }
    if (configurator instanceof PropertyConfigurator) {
        return ((PropertyConfigurator) configurator).getLogContextConfiguration();
    }
    return null;
}
 
Example #13
Source File: EmbeddedLogContext.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Attempts to clear the global log context used for embedded servers.
 */
static synchronized void clearLogContext() {
    final LogContext embeddedLogContext = Holder.LOG_CONTEXT;
    // Remove the configurator and clear the log context
    final Configurator configurator = embeddedLogContext.getLogger("").detach(Configurator.ATTACHMENT_KEY);
    // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext
    if (configurator instanceof PropertyConfigurator) {
        final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();
        clearLogContext(logContextConfiguration);
    } else if (configurator instanceof LogContextConfiguration) {
        clearLogContext((LogContextConfiguration) configurator);
    } else {
        // Remove all the handlers and close them as well as reset the loggers
        final List<String> loggerNames = Collections.list(embeddedLogContext.getLoggerNames());
        for (String name : loggerNames) {
            final Logger logger = embeddedLogContext.getLoggerIfExists(name);
            if (logger != null) {
                final Handler[] handlers = logger.clearHandlers();
                if (handlers != null) {
                    for (Handler handler : handlers) {
                        handler.close();
                    }
                }
                logger.setFilter(null);
                logger.setUseParentFilters(false);
                logger.setUseParentHandlers(true);
                logger.setLevel(Level.INFO);
            }
        }
    }
}
 
Example #14
Source File: BootableJar.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void configureLogging() throws IOException {
    if (!arguments.isVersion()) {
        LogContext ctx = configureLogContext();
        LogContext.setLogContextSelector(() -> {
            return ctx;
        });
    }
}
 
Example #15
Source File: LoggingOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ConfigurationPersistence getOrCreateConfigurationPersistence(final OperationContext context) {
    final PathAddress address = context.getCurrentAddress();
    final ConfigurationPersistence configurationPersistence;
    if (LoggingProfileOperations.isLoggingProfileAddress(address)) {
        final LogContext logContext = LoggingProfileContextSelector.getInstance().getOrCreate(LoggingProfileOperations.getLoggingProfileName(address));
        configurationPersistence = ConfigurationPersistence.getOrCreateConfigurationPersistence(logContext);
    } else {
        configurationPersistence = ConfigurationPersistence.getOrCreateConfigurationPersistence();
    }
    return configurationPersistence;
}
 
Example #16
Source File: LoggingOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ConfigurationPersistence getConfigurationPersistence(final OperationContext context) {
    final PathAddress address = context.getCurrentAddress();
    final LogContext logContext;
    if (LoggingProfileOperations.isLoggingProfileAddress(address)) {
        logContext = LoggingProfileContextSelector.getInstance().get(LoggingProfileOperations.getLoggingProfileName(address));
    } else {
        logContext = LogContext.getLogContext();
    }
    return ConfigurationPersistence.getConfigurationPersistence(logContext);
}
 
Example #17
Source File: LoggingOperationsSubsystemTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Logger getLogger(final String profileName) {
    final LogContext logContext;
    if (profileName != null) {
        logContext = LoggingProfileContextSelector.getInstance().get(profileName);
    } else {
        logContext = LogContext.getSystemLogContext();
    }
    return logContext.getLogger(FQCN);
}
 
Example #18
Source File: LoggingSubsystemRollbackTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
@BMRule(name = "Test logger rollback handler",
        targetClass = "org.jboss.as.logging.loggers.LoggerOperations$LoggerAddOperationStepHandler",
        targetMethod = "performRuntime",
        targetLocation = "AT EXIT",
        condition = "$1.getCurrentAddressValue().equals(\"org.jboss.as.logging.test\")",
        action = "$1.setRollbackOnly()"
)
public void testRollbackLogger() throws Exception {
    // Save the current model
    final ModelNode validSubsystemModel = getSubsystemModel(kernelServices);

    // The logger address
    final PathAddress address = createLoggerAddress("org.jboss.as.logging.test");

    // Operation should fail based on byteman script
    ModelNode op = SubsystemOperations.createAddOperation(address.toModelNode());
    ModelNode result = kernelServices.executeOperation(op);
    Assert.assertFalse("The add operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // Verify the loggers are not there - operation should fail on missing resource
    op = SubsystemOperations.createReadResourceOperation(address.toModelNode());
    result = kernelServices.executeOperation(op);
    Assert.assertFalse("The operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // verify the subsystem model matches the old model
    final ModelNode currentModel = getSubsystemModel(kernelServices);
    compare(validSubsystemModel, currentModel);

    final ConfigurationPersistence config = ConfigurationPersistence.getConfigurationPersistence(LogContext.getLogContext());
    compare(currentModel, config);
}
 
Example #19
Source File: LoggingSubsystemRollbackTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
@BMRule(name = "Test handler rollback handler",
        targetClass = "org.jboss.as.logging.handlers.HandlerOperations$HandlerAddOperationStepHandler",
        targetMethod = "performRuntime",
        targetLocation = "AT EXIT",
        condition = "$1.getCurrentAddressValue().equals(\"CONSOLE2\")",
        action = "$1.setRollbackOnly()")
public void testRollbackHandler() throws Exception {
    // Save the current model
    final ModelNode validSubsystemModel = getSubsystemModel(kernelServices);

    // Handler address
    final PathAddress address = createConsoleHandlerAddress("CONSOLE2");
    // Operation should fail based on byteman script
    ModelNode op = SubsystemOperations.createAddOperation(address.toModelNode());
    op.get(CommonAttributes.LEVEL.getName()).set("INFO");
    op.get(AbstractHandlerDefinition.FORMATTER.getName()).set("%d{HH:mm:ss,SSS} %-5p [%c] (%t) CONSOLE2: %s%e%n");
    ModelNode result = kernelServices.executeOperation(op);
    Assert.assertFalse("The add operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // Verify the loggers are not there - operation should fail on missing resource
    op = SubsystemOperations.createReadResourceOperation(address.toModelNode());
    result = kernelServices.executeOperation(op);
    Assert.assertFalse("The operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // verify the subsystem model matches the old model
    final ModelNode currentModel = getSubsystemModel(kernelServices);
    compare(validSubsystemModel, currentModel);

    final ConfigurationPersistence config = ConfigurationPersistence.getConfigurationPersistence(LogContext.getLogContext());
    compare(currentModel, config);
}
 
Example #20
Source File: LoggingSubsystemRollbackTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
@BMRules(rules = {
        @BMRule(name = "Test handler write-attribute rollback handler",
                targetClass = "org.jboss.as.logging.loggers.LoggerOperations$LoggerWriteAttributeHandler",
                targetMethod = "applyUpdate",
                targetLocation = "AT EXIT",
                condition = "$1.getCurrentAddressValue().equals(\"ROOT\")",
                action = "$1.setRollbackOnly()")
})
public void testRollbackRemoveProfile() throws Exception {
    // Save the current model
    final ModelNode validSubsystemModel = getSubsystemModel(kernelServices);

    final CompositeOperationBuilder compositeOperationBuilder = CompositeOperationBuilder.create();

    // The handler address to remove
    final PathAddress profileAddress = createAddress(CommonAttributes.LOGGING_PROFILE, PROFILE_NAME);
    // Remove the handler
    compositeOperationBuilder.addStep(SubsystemOperations.createRemoveOperation(profileAddress.toModelNode(), true));

    // Add a step to fail
    final ModelNode rootLoggerAddress = createRootLoggerAddress().toModelNode();
    compositeOperationBuilder.addStep(SubsystemOperations.createWriteAttributeOperation(rootLoggerAddress, CommonAttributes.LEVEL, "INFO"));

    ModelNode result = kernelServices.executeOperation(compositeOperationBuilder.build().getOperation());
    Assert.assertFalse("The update operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // verify the subsystem model matches the old model
    final ModelNode currentModel = getSubsystemModel(kernelServices);
    compare(validSubsystemModel, currentModel);

    ConfigurationPersistence config = ConfigurationPersistence.getConfigurationPersistence(LogContext.getLogContext());
    compare(currentModel, config);
    // Check the profile was rolled back
    config = ConfigurationPersistence.getConfigurationPersistence(LoggingProfileContextSelector.getInstance().get(PROFILE_NAME));
    compare(PROFILE_NAME, currentModel, config);
}
 
Example #21
Source File: LoggingSubsystemRollbackTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void rollbackAdd(final String profileName) throws Exception {
    // Save the current model
    final ModelNode validSubsystemModel = getSubsystemModel(kernelServices);

    // Add a handler to be removed
    final PathAddress consoleHandler = createConsoleHandlerAddress(profileName, "CONSOLE2");
    // Create a new handler
    ModelNode op = SubsystemOperations.createAddOperation(consoleHandler.toModelNode());
    op.get(CommonAttributes.LEVEL.getName()).set("INFO");
    op.get(AbstractHandlerDefinition.FORMATTER.getName()).set("%d{HH:mm:ss,SSS} %-5p [%c] (%t) CONSOLE2: %s%e%n");
    ModelNode result = kernelServices.executeOperation(op);
    Assert.assertFalse("The add operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // verify the subsystem model matches the old model
    ModelNode currentModel = getSubsystemModel(kernelServices);
    compare(profileName, validSubsystemModel, currentModel);

    final LogContext logContext = (profileName == null ? LogContext.getLogContext() : LoggingProfileContextSelector.getInstance().get(profileName));
    ConfigurationPersistence config = ConfigurationPersistence.getConfigurationPersistence(logContext);
    compare(profileName, currentModel, config);

    // Fail on a logger write attribute
    final PathAddress loggerAddress = createLoggerAddress(profileName, "org.jboss.as.logging.test");
    op = SubsystemOperations.createAddOperation(loggerAddress.toModelNode());
    result = kernelServices.executeOperation(op);
    Assert.assertFalse("The add operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // verify the subsystem model matches the old model
    currentModel = getSubsystemModel(kernelServices);
    compare(profileName, validSubsystemModel, currentModel);

    config = ConfigurationPersistence.getConfigurationPersistence(logContext);
    compare(profileName, currentModel, config);
}
 
Example #22
Source File: LoggingSubsystemRollbackTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void rollbackWriteAttribute(final String profileName) throws Exception {
    // Save the current model
    final ModelNode validSubsystemModel = getSubsystemModel(kernelServices);

    // Add a handler to be removed
    final PathAddress consoleHandler = createConsoleHandlerAddress(profileName, "CONSOLE");
    // Create a new handler
    ModelNode op = SubsystemOperations.createWriteAttributeOperation(consoleHandler.toModelNode(), ConsoleHandlerResourceDefinition.TARGET, "System.err");
    ModelNode result = kernelServices.executeOperation(op);
    Assert.assertFalse("The write operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // verify the subsystem model matches the old model
    ModelNode currentModel = getSubsystemModel(kernelServices);
    compare(profileName, validSubsystemModel, currentModel);

    final LogContext logContext = (profileName == null ? LogContext.getLogContext() : LoggingProfileContextSelector.getInstance().get(profileName));
    ConfigurationPersistence config = ConfigurationPersistence.getConfigurationPersistence(logContext);
    compare(profileName, currentModel, config);

    // Fail on a logger write attribute
    final PathAddress rootLoggerAddress = createRootLoggerAddress(profileName);
    op = SubsystemOperations.createWriteAttributeOperation(rootLoggerAddress.toModelNode(), CommonAttributes.LEVEL, "TRACE");
    result = kernelServices.executeOperation(op);
    Assert.assertFalse("The write operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // verify the subsystem model matches the old model
    currentModel = getSubsystemModel(kernelServices);
    compare(profileName, validSubsystemModel, currentModel);

    config = ConfigurationPersistence.getConfigurationPersistence(logContext);
    compare(profileName, currentModel, config);

}
 
Example #23
Source File: LoggingSubsystemRollbackTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void rollbackUpdateAttribute(final String profileName) throws Exception {
    // Save the current model
    final ModelNode validSubsystemModel = getSubsystemModel(kernelServices);

    // Add a handler to be removed
    final PathAddress consoleHandler = createConsoleHandlerAddress(profileName, "CONSOLE");
    // Create a new handler
    ModelNode op = SubsystemOperations.createOperation(AbstractHandlerDefinition.CHANGE_LEVEL_OPERATION_NAME, consoleHandler.toModelNode());
    op.get(CommonAttributes.LEVEL.getName()).set("DEBUG");
    ModelNode result = kernelServices.executeOperation(op);
    Assert.assertFalse("The update operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // verify the subsystem model matches the old model
    ModelNode currentModel = getSubsystemModel(kernelServices);
    compare(profileName, validSubsystemModel, currentModel);

    final LogContext logContext = (profileName == null ? LogContext.getLogContext() : LoggingProfileContextSelector.getInstance().get(profileName));
    ConfigurationPersistence config = ConfigurationPersistence.getConfigurationPersistence(logContext);
    compare(profileName, currentModel, config);

    // Fail on a logger write attribute
    final PathAddress rootLoggerAddress = createRootLoggerAddress(profileName);
    op = SubsystemOperations.createOperation("change-root-log-level", rootLoggerAddress.toModelNode());
    op.get(CommonAttributes.LEVEL.getName()).set("TRACE");
    result = kernelServices.executeOperation(op);
    Assert.assertFalse("The update operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // verify the subsystem model matches the old model
    currentModel = getSubsystemModel(kernelServices);
    compare(profileName, validSubsystemModel, currentModel);

    config = ConfigurationPersistence.getConfigurationPersistence(logContext);
    compare(profileName, currentModel, config);

}
 
Example #24
Source File: LoggingSubsystemRollbackTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void rollbackRemove(final String profileName) throws Exception {
    // Save the current model
    final ModelNode validSubsystemModel = getSubsystemModel(kernelServices);

    final CompositeOperationBuilder compositeOperationBuilder = CompositeOperationBuilder.create();

    // The handler address to remove
    final PathAddress consoleHandler = createConsoleHandlerAddress(profileName, "CONSOLE");
    // Remove the handler
    compositeOperationBuilder.addStep(SubsystemOperations.createRemoveOperation(consoleHandler.toModelNode()));

    // The logger to remove
    final PathAddress loggerAddress = createLoggerAddress(profileName, "org.jboss.as.logging");
    compositeOperationBuilder.addStep(SubsystemOperations.createRemoveOperation(loggerAddress.toModelNode()));

    // Add a step to fail
    final ModelNode rootLoggerAddress = createRootLoggerAddress(profileName).toModelNode();
    compositeOperationBuilder.addStep(SubsystemOperations.createWriteAttributeOperation(rootLoggerAddress, CommonAttributes.LEVEL, "INFO"));

    ModelNode result = kernelServices.executeOperation(compositeOperationBuilder.build().getOperation());
    Assert.assertFalse("The update operation should have failed, but was successful: " + result, SubsystemOperations.isSuccessfulOutcome(result));

    // verify the subsystem model matches the old model
    ModelNode currentModel = getSubsystemModel(kernelServices);
    compare(profileName, validSubsystemModel, currentModel);

    final LogContext logContext = (profileName == null ? LogContext.getLogContext() : LoggingProfileContextSelector.getInstance().get(profileName));
    ConfigurationPersistence config = ConfigurationPersistence.getConfigurationPersistence(logContext);
    compare(profileName, currentModel, config);

}
 
Example #25
Source File: WildFlyLogContextSelectorImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public LogContext getLogContext() {
    final LogContext localContext = this.localContext.get();
    if (localContext != null) {
        return localContext;
    }
    final int counter;
    synchronized (this) {
        counter = this.counter;
    }
    // If we have no registered contexts we can just use the default selector. This should improve performance
    // in most cases as the call stack will not be walked. This does depend on the on what was used for the
    // default selector, however in most cases it should perform better.
    return counter > 0 ? contextSelector.getLogContext() : defaultLogContextSelector.getLogContext();
}
 
Example #26
Source File: InheritableLevel.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public static InheritableLevel of(String str) {
    if (str.equalsIgnoreCase("inherit")) {
        return Inherited.INSTANCE;
    } else {
        return new ActualLevel(LogContext.getLogContext().getLevelForName(str.toUpperCase(Locale.ROOT)));
    }
}
 
Example #27
Source File: WildFlyLogContextSelectorImpl.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public LogContext setLocalContext(final LogContext newValue) {
    try {
        return localContext.get();
    } finally {
        if (newValue == null) {
            localContext.remove();
        } else {
            localContext.set(newValue);
        }
    }
}
 
Example #28
Source File: LoggingProfileContextSelector.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get or create the log context based on the logging profile.
 *
 * @param loggingProfile the logging profile to get or create the log context for
 *
 * @return the log context that was found or a new log context
 */
protected LogContext getOrCreate(final String loggingProfile) {
    LogContext result = profileContexts.get(loggingProfile);
    if (result == null) {
        result = LogContext.create();
        final LogContext current = profileContexts.putIfAbsent(loggingProfile, result);
        if (current != null) {
            result = current;
        }
    }
    return result;
}
 
Example #29
Source File: ConfigurationPersistence.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Gets the property configurator. If the {@link ConfigurationPersistence} does not exist a new one is created.
 *
 * @param logContext the log context used to find the property configurator or to attach it to.
 *
 * @return the property configurator
 */
public static ConfigurationPersistence getOrCreateConfigurationPersistence(final LogContext logContext) {
    final Logger root = logContext.getLogger(CommonAttributes.ROOT_LOGGER_NAME);
    final ConfigurationPersistence result;
    synchronized (LOCK) {
        Configurator configurator = root.getAttachment(Configurator.ATTACHMENT_KEY);
        if (configurator == null) {
            configurator = new ConfigurationPersistence(logContext);
            Configurator existing = root.attachIfAbsent(Configurator.ATTACHMENT_KEY, configurator);
            if (existing != null) {
                configurator = existing;
            }
        }
        if (configurator instanceof ConfigurationPersistence) {
            // We have the correct configurator
            result = (ConfigurationPersistence) configurator;
        } else if (configurator instanceof PropertyConfigurator) {
            // Create a new configurator delegating to the configurator found
            result = new ConfigurationPersistence((PropertyConfigurator) configurator);
            root.attach(Configurator.ATTACHMENT_KEY, result);
        } else {
            // An unknown configurator, log a warning and replace
            LoggingLogger.ROOT_LOGGER.replacingConfigurator(configurator);
            result = new ConfigurationPersistence(logContext);
            root.attach(Configurator.ATTACHMENT_KEY, result);
        }
    }
    return result;
}
 
Example #30
Source File: LoggingConfigurator.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 4 votes vote down vote up
/**
 * Construct an instance.
 */
public LoggingConfigurator() {
    this(LogContext.getSystemLogContext());
}