Java Code Examples for org.jboss.logmanager.config.LogContextConfiguration#getHandlerConfiguration()

The following examples show how to use org.jboss.logmanager.config.LogContextConfiguration#getHandlerConfiguration() . 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: SocketHandlerResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected OperationStepHandler additionalModelStep(final LogContextConfiguration logContextConfiguration) {
    return new OperationStepHandler() {
        @Override
        public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
            // If we don't require runtime steps to be executed we need to discard records on the delayed handler
            if (!requiresRuntime(context)) {
                HandlerConfiguration configuration = logContextConfiguration.getHandlerConfiguration(context.getCurrentAddressValue());
                if (configuration != null) {
                    if (!(configuration.getInstance() instanceof DelayedHandler)) {
                        throw LoggingLogger.ROOT_LOGGER.invalidType(DelayedHandler.class, configuration.getInstance().getClass());
                    }
                    final DelayedHandler delayedHandler = (DelayedHandler) configuration.getInstance();
                    // Clear any previous handlers and close them, then add the new handler
                    final Handler[] current = delayedHandler.setHandlers(new Handler[] {new DiscardingHandler()});
                    if (current != null) {
                        for (Handler handler : current) {
                            handler.close();
                        }
                    }
                }
            }
        }
    };
}
 
Example 2
Source File: SocketHandlerResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model, final LogContextConfiguration logContextConfiguration) throws OperationFailedException {
    final String name = context.getCurrentAddressValue();
    HandlerConfiguration configuration = logContextConfiguration.getHandlerConfiguration(name);
    if (configuration == null) {
        configuration = logContextConfiguration.addHandlerConfiguration(null, DelayedHandler.class.getName(), name);
    } else {
        if (!(configuration.getInstance() instanceof DelayedHandler)) {
            throw LoggingLogger.ROOT_LOGGER.invalidType(DelayedHandler.class, configuration.getInstance().getClass());
        }
    }
    ENABLED.setPropertyValue(context, model, configuration);
    final ModelNode filter = FILTER_SPEC.resolveModelAttribute(context, model);
    if (filter.isDefined()) {
        configuration.setFilter(filter.asString());
    }
    configuration.setLevel(LEVEL.resolvePropertyValue(context, model));
    configuration.setFormatterName(NAMED_FORMATTER.resolveModelAttribute(context, model).asString());
}
 
Example 3
Source File: HandlerOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model, final LogContextConfiguration logContextConfiguration) throws OperationFailedException {
    final String name = context.getCurrentAddressValue();
    final HandlerConfiguration configuration = logContextConfiguration.getHandlerConfiguration(name);
    if (configuration == null) {
        throw createOperationFailure(LoggingLogger.ROOT_LOGGER.handlerConfigurationNotFound(name));
    }
    // Get the handler name, uses the operation to get the single handler name being added
    final String handlerName = HANDLER_NAME.resolveModelAttribute(context, operation).asString();
    if (name.equals(handlerName)) {
        throw createOperationFailure(LoggingLogger.ROOT_LOGGER.cannotAddHandlerToSelf(configuration.getName()));
    }
    if (configuration.getHandlerNames().contains(handlerName)) {
        LoggingLogger.ROOT_LOGGER.tracef("Handler %s is already assigned to handler %s", handlerName, handlerName);
    } else {
        configuration.addHandlerName(handlerName);
    }
}
 
Example 4
Source File: HandlerOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Enables the handler if it was previously disabled.
 * <p/>
 * If it was not previously disable, nothing happens.
 *
 * @param configuration the log context configuration.
 * @param handlerName   the name of the handler to enable.
 */
private static void enableHandler(final LogContextConfiguration configuration, final String handlerName) {
    final HandlerConfiguration handlerConfiguration = configuration.getHandlerConfiguration(handlerName);
    try {
        handlerConfiguration.setPropertyValueString("enabled", "true");
        return;
    } catch (IllegalArgumentException e) {
        // do nothing
    }
    final Map<String, String> disableHandlers = configuration.getLogContext().getAttachment(CommonAttributes.ROOT_LOGGER_NAME, DISABLED_HANDLERS_KEY);
    if (disableHandlers != null && disableHandlers.containsKey(handlerName)) {
        synchronized (HANDLER_LOCK) {
            final String filter = disableHandlers.get(handlerName);
            handlerConfiguration.setFilter(filter);
            disableHandlers.remove(handlerName);
        }
    }
}
 
Example 5
Source File: HandlerOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Disables the handler if the handler exists and is not already disabled.
 * <p/>
 * If the handler does not exist or is already disabled nothing happens.
 *
 * @param configuration the log context configuration.
 * @param handlerName   the handler name to disable.
 */
private static void disableHandler(final LogContextConfiguration configuration, final String handlerName) {
    final HandlerConfiguration handlerConfiguration = configuration.getHandlerConfiguration(handlerName);
    try {
        handlerConfiguration.setPropertyValueString("enabled", "false");
        return;
    } catch (IllegalArgumentException e) {
        // do nothing
    }
    final Logger root = configuration.getLogContext().getLogger(CommonAttributes.ROOT_LOGGER_NAME);
    Map<String, String> disableHandlers = root.getAttachment(DISABLED_HANDLERS_KEY);
    synchronized (HANDLER_LOCK) {
        if (disableHandlers == null) {
            disableHandlers = new HashMap<String, String>();
            final Map<String, String> current = root.attachIfAbsent(DISABLED_HANDLERS_KEY, disableHandlers);
            if (current != null) {
                disableHandlers = current;
            }
        }
        if (!disableHandlers.containsKey(handlerName)) {
            disableHandlers.put(handlerName, handlerConfiguration.getFilter());
            handlerConfiguration.setFilter(CommonAttributes.DENY.getName());
        }
    }
}
 
Example 6
Source File: SocketHandlerResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
protected boolean applyUpdate(final OperationContext context, final String attributeName, final String addressName,
                              final ModelNode value, final LogContextConfiguration logContextConfiguration) throws OperationFailedException {

    // First get the handler configuration.
    final HandlerConfiguration configuration = logContextConfiguration.getHandlerConfiguration(addressName);
    if (configuration == null) {
        throw createOperationFailure(LoggingLogger.ROOT_LOGGER.handlerConfigurationNotFound(addressName));
    }
    // Handle writing the attribute
    if (LEVEL.getName().equals(attributeName)) {
        configuration.setLevel(value.asString());
    } else if (NAMED_FORMATTER.getName().equals(attributeName)) {
        if (value.isDefined()) {
            configuration.setFormatterName(value.asString());
        } else {
            configuration.setFormatterName(null);
        }
    } else if (FILTER_SPEC.getName().equals(attributeName)) {
        if (value.isDefined()) {
            configuration.setFilter(value.asString());
        } else {
            configuration.setFilter(null);
        }
    }
    return Logging.requiresReload(getAttributeDefinition(attributeName).getFlags());

}
 
Example 7
Source File: HandlerOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public final void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model, final LogContextConfiguration logContextConfiguration) throws OperationFailedException {
    final String name = context.getCurrentAddressValue();
    final HandlerConfiguration configuration = logContextConfiguration.getHandlerConfiguration(name);
    if (configuration == null) {
        throw createOperationFailure(LoggingLogger.ROOT_LOGGER.handlerConfigurationNotFound(name));
    }
    final AttributeDefinition[] attributes = getAttributes();
    if (attributes != null) {
        boolean restartRequired = false;
        boolean reloadRequired = false;
        for (AttributeDefinition attribute : attributes) {
            // Only update if the attribute is on the operation
            if (operation.has(attribute.getName())) {
                handleProperty(attribute, context, model, logContextConfiguration, configuration);
                restartRequired = restartRequired || Logging.requiresRestart(attribute.getFlags());
                reloadRequired = reloadRequired || Logging.requiresReload(attribute.getFlags());
            }
        }
        if (restartRequired) {
            context.restartRequired();
        } else if (reloadRequired) {
            context.reloadRequired();
        }
    }

    // It's important that properties are written in the correct order, reorder the properties if
    // needed before the commit.
    addOrderPropertiesStep(context, propertySorter, configuration);
}
 
Example 8
Source File: HandlerOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model, final LogContextConfiguration logContextConfiguration) throws OperationFailedException {
    final String name = context.getCurrentAddressValue();
    final HandlerConfiguration configuration = logContextConfiguration.getHandlerConfiguration(name);
    if (configuration == null) {
        throw createOperationFailure(LoggingLogger.ROOT_LOGGER.handlerConfigurationNotFound(name));
    }
    // Uses the operation to get the single handler name being added
    configuration.removeHandlerName(HANDLER_NAME.resolveModelAttribute(context, operation).asString());
}
 
Example 9
Source File: HandlerResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
protected void updateModel(final LogContextConfiguration logContextConfiguration, final String name, final ModelNode model) {
    final HandlerConfiguration handlerConfiguration = logContextConfiguration.getHandlerConfiguration(name);
    updateModel(handlerConfiguration, model);

}
 
Example 10
Source File: HandlerOperations.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
protected boolean applyUpdate(final OperationContext context, final String attributeName, final String addressName, final ModelNode value, final LogContextConfiguration logContextConfiguration) throws OperationFailedException {
    boolean restartRequired = false;
    if (logContextConfiguration.getHandlerNames().contains(addressName)) {
        final HandlerConfiguration configuration = logContextConfiguration.getHandlerConfiguration(addressName);
        if (LEVEL.getName().equals(attributeName)) {
            handleProperty(LEVEL, context, value, logContextConfiguration, configuration, false);
            handleProperty(LEVEL, context, value, logContextConfiguration, configuration, false);
        } else if (FILTER.getName().equals(attributeName)) {
            // Filter should be replaced by the filter-spec in the super class
            handleProperty(FILTER_SPEC, context, value, logContextConfiguration, configuration, false);
        } else if (FILTER_SPEC.getName().equals(attributeName)) {
            handleProperty(FILTER_SPEC, context, value, logContextConfiguration, configuration, false);
        } else if (FORMATTER.getName().equals(attributeName)) {
            handleProperty(FORMATTER, context, value, logContextConfiguration, configuration, false);
        } else if (ENCODING.getName().equals(attributeName)) {
            handleProperty(ENCODING, context, value, logContextConfiguration, configuration, false);
        } else if (SUBHANDLERS.getName().equals(attributeName)) {
            handleProperty(SUBHANDLERS, context, value, logContextConfiguration, configuration, false);
        } else if (PROPERTIES.getName().equals(attributeName)) {
            final PropertyConfigurable propertyConfigurable;
            // A POJO configuration will have the same name as the handler
            final PojoConfiguration pojoConfiguration = logContextConfiguration.getPojoConfiguration(configuration.getName());
            if (pojoConfiguration == null) {
                propertyConfigurable = configuration;
            } else {
                propertyConfigurable = pojoConfiguration;
                // A log4j appender may be an OptionHandler which requires the invocation of activateOptions(). Setting
                // a dummy property on the Log4jAppenderHandler is required to invoke this method as all properties are
                // set on the POJO which is the actual appender
                configuration.setPropertyValueString(Log4jAppenderHandler.ACTIVATOR_PROPERTY_METHOD_NAME, "");
            }
            if (value.isDefined()) {
                for (Property property : value.asPropertyList()) {
                    propertyConfigurable.setPropertyValueString(property.getName(), property.getValue().asString());
                }
            } else {
                final List<String> propertyNames = propertyConfigurable.getPropertyNames();
                for (String propertyName : propertyNames) {
                    // Ignore the enable attribute if found
                    if ("enabled".equals(propertyName)) continue;
                    propertyConfigurable.removeProperty(propertyName);
                    // Set to restart required if undefining properties
                    restartRequired = true;
                }
            }
        } else if (QUEUE_LENGTH.getName().equals(attributeName)) {
            // queue-length is a construction parameter, runtime changes are not allowed
            restartRequired = true;
        } else {
            for (AttributeDefinition attribute : getAttributes()) {
                if (attribute.getName().equals(attributeName)) {
                    handleProperty(attribute, context, value, logContextConfiguration, configuration, false);
                    restartRequired = Logging.requiresReload(attribute.getFlags());
                    break;
                }
            }
        }

        // It's important that properties are written in the correct order, reorder the properties if
        // needed before the commit.
        addOrderPropertiesStep(context, propertySorter, configuration);
    }
    return restartRequired;
}
 
Example 11
Source File: HandlerOperationsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Tests a composite operation of undefining a {@code formatter} attribute and defining a {@code named-formatter}
 * attribute in a composite operation. These two specific attributes have strange behavior. If the
 * {@code named-formatter} is defined it removes the formatter, named the same as the handler, which was created
 * as part of the {@code undefine-attribute} operation of the {@code formatter} attribute.
 *
 */
@Test
public void testCompositeOperations() {
    final ModelNode address = createFileHandlerAddress("FILE").toModelNode();
    final String filename = "test-file.log";
    final String defaultFormatterName = "FILE" + PatternFormatterResourceDefinition.DEFAULT_FORMATTER_SUFFIX;

    // Add the handler
    ModelNode addOp = OperationBuilder.createAddOperation(address)
            .addAttribute(CommonAttributes.FILE, createFileValue("jboss.server.log.dir", filename))
            .build();
    executeOperation(kernelServices, addOp);
    final ModelNode patternFormatterAddress = createPatternFormatterAddress("PATTERN").toModelNode();
    addOp = SubsystemOperations.createAddOperation(patternFormatterAddress);
    addOp.get(PatternFormatterResourceDefinition.PATTERN.getName()).set("%d{HH:mm:ss,SSS} %-5p [%c] %s%e%n");
    executeOperation(kernelServices, addOp);

    // Create a composite operation to undefine
    final Operation op = CompositeOperationBuilder.create()
            .addStep(SubsystemOperations.createUndefineAttributeOperation(address, "formatter"))
            .addStep(SubsystemOperations.createWriteAttributeOperation(address, "named-formatter", "PATTERN"))
            .build();
    executeOperation(kernelServices, op.getOperation());

    // Get the log context configuration to validate what has been configured
    final LogContextConfiguration configuration = ConfigurationPersistence.getConfigurationPersistence(LogContext.getLogContext());
    assertNotNull("Expected to find the configuration", configuration);
    assertFalse("Expected the default formatter named " + defaultFormatterName + " to be removed for the handler FILE",
            configuration.getFormatterNames().contains(defaultFormatterName));
    final HandlerConfiguration handlerConfiguration = configuration.getHandlerConfiguration("FILE");
    assertNotNull("Expected to find the configuration for the FILE handler", configuration);
    assertEquals("Expected the handler named FILE to use the PATTERN formatter", "PATTERN",
            handlerConfiguration.getFormatterName());

    // Undefine the named-formatter to ensure a formatter is created
    executeOperation(kernelServices, SubsystemOperations.createUndefineAttributeOperation(address, "named-formatter"));
    assertTrue("Expected the default formatter named " + defaultFormatterName + " to be added",
            configuration.getFormatterNames().contains(defaultFormatterName));
    assertEquals("Expected the handler named FILE to use the FILE formatter", defaultFormatterName,
            handlerConfiguration.getFormatterName());
}
 
Example 12
Source File: HandlerOperationsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testAddHandlerComposite() {
    final ModelNode handlerAddress = createFileHandlerAddress("FILE").toModelNode();
    final String filename = "test-file-2.log";

    final CompositeOperationBuilder builder = CompositeOperationBuilder.create();

    // Add the handler
    builder.addStep(OperationBuilder.createAddOperation(handlerAddress)
            .addAttribute(CommonAttributes.FILE, createFileValue("jboss.server.log.dir", filename))
            .build());

    // Create a formatter and add it
    final ModelNode patternFormatterAddress = createPatternFormatterAddress("PATTERN").toModelNode();
    builder.addStep(OperationBuilder.createAddOperation(patternFormatterAddress)
            .addAttribute(PatternFormatterResourceDefinition.PATTERN, "%d{HH:mm:ss,SSS} %-5p [%c] %s%e%n")
            .build());

    // Write the named-formatter
    builder.addStep(SubsystemOperations.createWriteAttributeOperation(handlerAddress, "named-formatter", "PATTERN"));

    // Create an async-handler
    final ModelNode asyncHandlerAddress = createAsyncHandlerAddress(null, "ASYNC").toModelNode();
    builder.addStep(OperationBuilder.createAddOperation(asyncHandlerAddress)
            .addAttribute(AsyncHandlerResourceDefinition.QUEUE_LENGTH, 100)
            .build());

    // Add the file-handler to the async-handler
    ModelNode addHandlerOp = SubsystemOperations.createOperation("add-handler", asyncHandlerAddress);
    addHandlerOp.get("name").set("FILE");
    builder.addStep(addHandlerOp);

    // Create a logger
    final ModelNode loggerAddress = createLoggerAddress("org.jboss.as.logging").toModelNode();
    builder.addStep(SubsystemOperations.createAddOperation(loggerAddress));

    // Use the add-handler operation to add the handler to the logger
    addHandlerOp = SubsystemOperations.createOperation("add-handler", loggerAddress);
    addHandlerOp.get("name").set("ASYNC");
    builder.addStep(addHandlerOp);

    executeOperation(kernelServices, builder.build().getOperation());

    // Get the log context configuration to validate what has been configured
    final LogContextConfiguration configuration = ConfigurationPersistence.getConfigurationPersistence(LogContext.getLogContext());
    assertNotNull("Expected to find the configuration", configuration);
    final HandlerConfiguration handlerConfiguration = configuration.getHandlerConfiguration("FILE");
    assertNotNull("Expected to find the configuration for the FILE handler", configuration);
    assertEquals("Expected the handler named FILE to use the PATTERN formatter", "PATTERN",
            handlerConfiguration.getFormatterName());
    final LoggerConfiguration loggerConfiguration = configuration.getLoggerConfiguration("org.jboss.as.logging");
    assertNotNull("Expected the logger configuration for org.jboss.as.logging to exist", loggerConfiguration);
    assertTrue("Expected the FILE handler to be assigned", loggerConfiguration.getHandlerNames().contains("ASYNC"));
}