org.jboss.logmanager.Logger Java Examples

The following examples show how to use org.jboss.logmanager.Logger. 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: 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 #2
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 #3
Source File: LoggingSetupRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void addNamedHandlersToCategory(CategoryConfig categoryConfig, Map<String, Handler> namedHandlers,
        Logger categoryLogger,
        ErrorManager errorManager) {
    for (String categoryNamedHandler : categoryConfig.handlers.get()) {
        if (namedHandlers.get(categoryNamedHandler) != null) {
            categoryLogger.addHandler(namedHandlers.get(categoryNamedHandler));
        } else {
            errorManager.error(String.format("Handler with name '%s' is linked to a category but not configured.",
                    categoryNamedHandler), null, ErrorManager.GENERIC_FAILURE);
        }
    }
}
 
Example #4
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 #5
Source File: WildFlyLogContextSelector.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void clearLogContext() {
    // Remove the configurator and clear the log context
    final Configurator configurator = EMBEDDED_LOG_CONTEXT.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(EMBEDDED_LOG_CONTEXT.getLoggerNames());
        for (String name : loggerNames) {
            final Logger logger = EMBEDDED_LOG_CONTEXT.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 #6
Source File: LoggingOperationsSubsystemTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void doLog(final String loggingProfile, final Level[] levels, final String format, final Object... params) {
    final Logger log = getLogger(loggingProfile);
    // log a message
    for (Level lvl : levels) {
        log.log(lvl, String.format(format, params));
    }
}
 
Example #7
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 #8
Source File: Main.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * The main method.
 *
 * @param args the command-line arguments
 */
public static void main(String[] args) throws IOException {
    MDC.put("process", "host controller");


    // Grab copies of our streams.
    final InputStream in = System.in;
    //final PrintStream out = System.out;
    //final PrintStream err = System.err;

    byte[] authKey = new byte[ProcessController.AUTH_BYTES_ENCODED_LENGTH];
    try {
        StreamUtils.readFully(new Base64InputStream(System.in), authKey);
    } catch (IOException e) {
        STDERR.println(HostControllerLogger.ROOT_LOGGER.failedToReadAuthenticationKey(e));
        fail();
        return;
    }

    // Make sure our original stdio is properly captured.
    try {
        Class.forName(ConsoleHandler.class.getName(), true, ConsoleHandler.class.getClassLoader());
    } catch (Throwable ignored) {
    }

    // Install JBoss Stdio to avoid any nasty crosstalk.
    StdioContext.install();
    final StdioContext context = StdioContext.create(
        new NullInputStream(),
        new LoggingOutputStream(Logger.getLogger("stdout"), Level.INFO),
        new LoggingOutputStream(Logger.getLogger("stderr"), Level.ERROR)
    );
    StdioContext.setStdioContextSelector(new SimpleStdioContextSelector(context));

    create(args, new String(authKey, Charset.forName("US-ASCII")));

    while (in.read() != -1) {}
    exit();
}
 
Example #9
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 #10
Source File: VertxLogDelegate.java    From quarkus with Apache License 2.0 4 votes vote down vote up
public VertxLogDelegate(String name) {
    this.logger = Logger.getLogger(name);
}
 
Example #11
Source File: HandlerOperationsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Test
public void testFormatsNoColor() throws Exception {
    final Path logFile = LoggingTestEnvironment.get().getLogDir().resolve("formatter.log");
    // Delete the file if it exists
    Files.deleteIfExists(logFile);

    // Create a file handler
    final String fileHandlerName = "formatter-handler";
    final ModelNode handlerAddress = createFileHandlerAddress(fileHandlerName).toModelNode();
    ModelNode op = SubsystemOperations.createAddOperation(handlerAddress);
    op.get(CommonAttributes.LEVEL.getName()).set("INFO");
    op.get(CommonAttributes.ENCODING.getName()).set(ENCODING);
    op.get(CommonAttributes.FILE.getName()).get(PathResourceDefinition.PATH.getName()).set(logFile.toAbsolutePath().toString());
    op.get(CommonAttributes.AUTOFLUSH.getName()).set(true);
    op.get(FileHandlerResourceDefinition.FORMATTER.getName()).set("%s%n");
    executeOperation(kernelServices, op);

    // Create a logger
    final Logger logger = LogContext.getSystemLogContext().getLogger(HandlerOperationsTestCase.class.getName());
    final ModelNode loggerAddress = createLoggerAddress(logger.getName()).toModelNode();
    op = SubsystemOperations.createAddOperation(loggerAddress);
    op.get(LoggerResourceDefinition.USE_PARENT_HANDLERS.getName()).set(false);
    op.get(LoggerAttributes.HANDLERS.getName()).setEmptyList().add(fileHandlerName);
    executeOperation(kernelServices, op);

    // Log a few records
    logger.log(Level.INFO, "Test message 1");
    logger.log(Level.INFO, "Test message 2");

    // Read the file
    List<String> lines = Files.readAllLines(logFile, StandardCharsets.UTF_8);
    assertEquals("Number of lines logged and found in the file do not match", 2, lines.size());

    // Check the lines
    assertEquals("Test message 1", lines.get(0));
    assertEquals("Test message 2", lines.get(1));

    // Create a pattern formatter
    final ModelNode patternFormatterAddress = createPatternFormatterAddress("PATTERN").toModelNode();
    op = SubsystemOperations.createAddOperation(patternFormatterAddress);
    op.get(PatternFormatterResourceDefinition.PATTERN.getName()).set("[changed-pattern] %s%n");
    executeOperation(kernelServices, op);

    // The formatter will need to be undefined before the named-formatter can be written
    executeOperation(kernelServices, SubsystemOperations.createUndefineAttributeOperation(handlerAddress, FileHandlerResourceDefinition.FORMATTER));
    // Assign the pattern to the handler
    executeOperation(kernelServices, SubsystemOperations.createWriteAttributeOperation(handlerAddress, FileHandlerResourceDefinition.NAMED_FORMATTER, "PATTERN"));

    // Check that the formatter attribute was undefined
    op = SubsystemOperations.createReadAttributeOperation(handlerAddress, FileHandlerResourceDefinition.FORMATTER);
    op.get("include-defaults").set(false);
    ModelNode result = executeOperation(kernelServices, op);
    assertFalse("formatter attribute was not undefined after the change to a named-formatter", SubsystemOperations.readResult(result).isDefined());

    // Log some more records
    logger.log(Level.INFO, "Test message 3");
    logger.log(Level.INFO, "Test message 4");

    // Read the file
    lines = Files.readAllLines(logFile, StandardCharsets.UTF_8);
    assertEquals("Number of lines logged and found in the file do not match", 4, lines.size());

    // Check the lines
    assertTrue("Line logged does not match expected: 3", Arrays.equals("[changed-pattern] Test message 3".getBytes(ENCODING), lines.get(2).getBytes(ENCODING)));
    // Second line will start with the clear string, followed by the color string
    assertTrue("Line logged does not match expected: 4", Arrays.equals("[changed-pattern] Test message 4".getBytes(ENCODING), lines.get(3).getBytes(ENCODING)));

    // Remove the handler operation
    final ModelNode removeHandlerOp = SubsystemOperations.createOperation("remove-handler", loggerAddress);
    removeHandlerOp.get("name").set(fileHandlerName);

    // Finally clean everything up
    op = SubsystemOperations.CompositeOperationBuilder.create()
            .addStep(removeHandlerOp)
            .addStep(SubsystemOperations.createRemoveOperation(handlerAddress))
            .addStep(SubsystemOperations.createRemoveOperation(patternFormatterAddress))
            .addStep(SubsystemOperations.createRemoveOperation(loggerAddress))
            .build().getOperation();
    executeOperation(kernelServices, op);

}
 
Example #12
Source File: LoggingOperationsSubsystemTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void testDisableHandler(final String profileName, boolean legacy) throws Exception {
    final String fileHandlerName = "test-file-handler";

    final Path 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, LoggerAttributes.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("disable", 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 = Files.readAllLines(logFile, StandardCharsets.UTF_8);
    assertEquals("Handler was not disable.", 3, lines.size());

    // Re-enable the handler
    ModelNode enableOp = legacy ? Util.getEmptyOperation("enable", 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 = Files.readAllLines(logFile, StandardCharsets.UTF_8);
    assertEquals("Handler was not disable.", 6, lines.size());

}
 
Example #13
Source File: LoggingOperationsSubsystemTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void testPatternFormatter(final String profileName) throws Exception {
    final String fileHandlerName = "test-file-handler";

    final Path 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(LoggerAttributes.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 = Files.readAllLines(logFile, StandardCharsets.UTF_8);
    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);

}
 
Example #14
Source File: RootSubsystemOperationsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void testReadLogFile(final KernelServices kernelServices, final ModelNode op, final Logger logger) {
    // Log some messages
    for (int i = 0; i < 50; i++) {
        logger.info(msg + i);
    }

    ModelNode result = executeOperation(kernelServices, op);
    List<String> logLines = SubsystemOperations.readResultAsList(result);
    assertEquals(10, logLines.size());
    checkLogLines(logLines, 40);

    // Read from top
    op.get("tail").set(false);
    result = executeOperation(kernelServices, op);
    logLines = SubsystemOperations.readResultAsList(result);
    assertEquals(10, logLines.size());
    checkLogLines(logLines, 0);

    // Read more lines from top
    op.get("lines").set(20);
    result = executeOperation(kernelServices, op);
    logLines = SubsystemOperations.readResultAsList(result);
    assertEquals(20, logLines.size());
    checkLogLines(logLines, 0);

    // Read from bottom
    op.get("tail").set(true);
    result = executeOperation(kernelServices, op);
    logLines = SubsystemOperations.readResultAsList(result);
    assertEquals(20, logLines.size());
    checkLogLines(logLines, 30);

    // Skip lines from bottom
    op.get("tail").set(true);
    op.get("skip").set(5);
    result = executeOperation(kernelServices, op);
    logLines = SubsystemOperations.readResultAsList(result);
    assertEquals(20, logLines.size());
    checkLogLines(logLines, 25);

    // Skip lines from top
    op.get("tail").set(false);
    op.get("skip").set(5);
    result = executeOperation(kernelServices, op);
    logLines = SubsystemOperations.readResultAsList(result);
    assertEquals(20, logLines.size());
    checkLogLines(logLines, 5);

    // Read all lines
    op.get("tail").set(false);
    op.get("lines").set(-1);
    op.remove("skip");
    result = executeOperation(kernelServices, op);
    logLines = SubsystemOperations.readResultAsList(result);
    assertEquals(50, logLines.size());
    checkLogLines(logLines, 0);

    // Read all lines, but 5 lines
    op.get("tail").set(false);
    op.get("lines").set(-1);
    op.get("skip").set(5);
    result = executeOperation(kernelServices, op);
    logLines = SubsystemOperations.readResultAsList(result);
    assertEquals(45, logLines.size());
    checkLogLines(logLines, 5);
}
 
Example #15
Source File: RootSubsystemOperationsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private Logger getLogger() {
    return LogContext.getSystemLogContext().getLogger("org.jboss.as.logging.test");
}
 
Example #16
Source File: RootSubsystemOperationsTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
private Logger getLogger(final String loggingProfile) {
    return LoggingProfileContextSelector.getInstance().get(loggingProfile).getLogger("org.jboss.as.logging.test");
}