Search in sources :

Example 6 with Logger

use of org.jboss.logmanager.Logger in project quarkus by quarkusio.

the class LoggingSetupRecorder method initializeBuildTimeLogging.

public static void initializeBuildTimeLogging(LogConfig config, LogBuildTimeConfig buildConfig, ConsoleRuntimeConfig consoleConfig, LaunchMode launchMode) {
    final Map<String, CategoryConfig> categories = config.categories;
    final LogContext logContext = LogContext.getLogContext();
    final Logger rootLogger = logContext.getLogger("");
    rootLogger.setLevel(config.level);
    ErrorManager errorManager = new OnlyOnceErrorManager();
    final Map<String, CleanupFilterConfig> filters = config.filters;
    List<LogCleanupFilterElement> filterElements = new ArrayList<>(filters.size());
    for (Entry<String, CleanupFilterConfig> entry : filters.entrySet()) {
        filterElements.add(new LogCleanupFilterElement(entry.getKey(), entry.getValue().targetLevel, entry.getValue().ifStartsWith));
    }
    LogCleanupFilter logCleanupFilter = new LogCleanupFilter(filterElements);
    final ArrayList<Handler> handlers = new ArrayList<>(3);
    if (config.console.enable) {
        final Handler consoleHandler = configureConsoleHandler(config.console, consoleConfig, errorManager, logCleanupFilter, Collections.emptyList(), new RuntimeValue<>(Optional.empty()), launchMode);
        errorManager = consoleHandler.getErrorManager();
        handlers.add(consoleHandler);
    }
    Map<String, Handler> namedHandlers = createNamedHandlers(config, consoleConfig, Collections.emptyList(), errorManager, logCleanupFilter, launchMode);
    for (Map.Entry<String, CategoryConfig> entry : categories.entrySet()) {
        final String categoryName = entry.getKey();
        final Level logLevel = getLogLevel(categoryName, categories, CategoryConfig::getLevel, buildConfig.minLevel);
        final Level minLogLevel = getLogLevel(categoryName, buildConfig.categories, CategoryBuildTimeConfig::getMinLevel, buildConfig.minLevel);
        if (logLevel.intValue() < minLogLevel.intValue()) {
            log.warnf("Log level %s for category '%s' set below minimum logging level %s, promoting it to %s", logLevel, entry.getKey(), minLogLevel, minLogLevel);
            entry.getValue().level = InheritableLevel.of(minLogLevel.toString());
        }
    }
    for (Map.Entry<String, CategoryConfig> entry : categories.entrySet()) {
        final String name = entry.getKey();
        final Logger categoryLogger = logContext.getLogger(name);
        final CategoryConfig categoryConfig = entry.getValue();
        if (!categoryConfig.level.isInherited()) {
            categoryLogger.setLevel(categoryConfig.level.getLevel());
        }
        categoryLogger.setUseParentHandlers(categoryConfig.useParentHandlers);
        if (categoryConfig.handlers.isPresent()) {
            addNamedHandlersToCategory(categoryConfig, namedHandlers, categoryLogger, errorManager);
        }
    }
    InitialConfigurator.DELAYED_HANDLER.setAutoFlush(false);
    InitialConfigurator.DELAYED_HANDLER.setBuildTimeHandlers(handlers.toArray(EmbeddedConfigurator.NO_HANDLERS));
}
Also used : OnlyOnceErrorManager(org.jboss.logmanager.errormanager.OnlyOnceErrorManager) ErrorManager(java.util.logging.ErrorManager) ArrayList(java.util.ArrayList) LogContext(org.jboss.logmanager.LogContext) SyslogHandler(org.jboss.logmanager.handlers.SyslogHandler) FileHandler(org.jboss.logmanager.handlers.FileHandler) PeriodicSizeRotatingFileHandler(org.jboss.logmanager.handlers.PeriodicSizeRotatingFileHandler) ConsoleHandler(org.jboss.logmanager.handlers.ConsoleHandler) SizeRotatingFileHandler(org.jboss.logmanager.handlers.SizeRotatingFileHandler) Handler(java.util.logging.Handler) AsyncHandler(org.jboss.logmanager.handlers.AsyncHandler) Logger(org.jboss.logmanager.Logger) OnlyOnceErrorManager(org.jboss.logmanager.errormanager.OnlyOnceErrorManager) Level(java.util.logging.Level) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with Logger

use of org.jboss.logmanager.Logger in project wildfly-core by wildfly.

the class LoggingOperationsSubsystemTestCase method testDisableHandler.

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());
}
Also used : Path(java.nio.file.Path) ModelNode(org.jboss.dmr.ModelNode) Logger(org.jboss.logmanager.Logger)

Example 8 with Logger

use of org.jboss.logmanager.Logger in project wildfly-core by wildfly.

the class HandlerOperations method disableHandler.

/**
 * 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());
        }
    }
}
Also used : HandlerConfiguration(org.jboss.logmanager.config.HandlerConfiguration) LoggingLogger(org.jboss.as.logging.logging.LoggingLogger) Logger(org.jboss.logmanager.Logger)

Example 9 with Logger

use of org.jboss.logmanager.Logger in project wildfly-core by wildfly.

the class EmbeddedLogContext method clearLogContext.

/**
 * 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);
            }
        }
    }
}
Also used : LogContextConfiguration(org.jboss.logmanager.config.LogContextConfiguration) PropertyConfigurator(org.jboss.logmanager.PropertyConfigurator) Configurator(org.jboss.logmanager.Configurator) LogContext(org.jboss.logmanager.LogContext) Handler(java.util.logging.Handler) List(java.util.List) Logger(org.jboss.logmanager.Logger) PropertyConfigurator(org.jboss.logmanager.PropertyConfigurator)

Example 10 with Logger

use of org.jboss.logmanager.Logger in project quarkus by quarkusio.

the class LoggingSetupRecorder method initializeLogging.

public void initializeLogging(LogConfig config, LogBuildTimeConfig buildConfig, final boolean enableWebStream, final RuntimeValue<Optional<Handler>> devUiConsoleHandler, final List<RuntimeValue<Optional<Handler>>> additionalHandlers, final List<RuntimeValue<Map<String, Handler>>> additionalNamedHandlers, final List<RuntimeValue<Optional<Formatter>>> possibleFormatters, final RuntimeValue<Optional<Supplier<String>>> possibleBannerSupplier, LaunchMode launchMode) {
    final Map<String, CategoryConfig> categories = config.categories;
    final LogContext logContext = LogContext.getLogContext();
    final Logger rootLogger = logContext.getLogger("");
    if (config.level.intValue() < buildConfig.minLevel.intValue()) {
        log.warnf("Root log level %s set below minimum logging level %s, promoting it to %s", config.level, buildConfig.minLevel, buildConfig.minLevel);
        rootLogger.setLevel(buildConfig.minLevel);
    } else {
        rootLogger.setLevel(config.level);
    }
    ErrorManager errorManager = new OnlyOnceErrorManager();
    final Map<String, CleanupFilterConfig> filters = config.filters;
    List<LogCleanupFilterElement> filterElements;
    if (filters.isEmpty()) {
        filterElements = Collections.emptyList();
    } else {
        filterElements = new ArrayList<>(filters.size());
        filters.forEach(new BiConsumer<String, CleanupFilterConfig>() {

            @Override
            public void accept(String loggerName, CleanupFilterConfig config) {
                filterElements.add(new LogCleanupFilterElement(loggerName, config.targetLevel, config.ifStartsWith));
            }
        });
    }
    LogCleanupFilter cleanupFiler = new LogCleanupFilter(filterElements);
    for (Handler handler : LogManager.getLogManager().getLogger("").getHandlers()) {
        handler.setFilter(cleanupFiler);
    }
    final ArrayList<Handler> handlers = new ArrayList<>(3 + additionalHandlers.size());
    if (config.console.enable) {
        final Handler consoleHandler = configureConsoleHandler(config.console, consoleRuntimeConfig.getValue(), errorManager, cleanupFiler, possibleFormatters, possibleBannerSupplier, launchMode);
        errorManager = consoleHandler.getErrorManager();
        handlers.add(consoleHandler);
    }
    if (launchMode.isDevOrTest()) {
        handlers.add(new Handler() {

            @Override
            public void publish(LogRecord record) {
                if (record.getThrown() != null) {
                    ExceptionReporting.notifyException(record.getThrown());
                }
            }

            @Override
            public void flush() {
            }

            @Override
            public void close() throws SecurityException {
            }
        });
    }
    if (config.file.enable) {
        handlers.add(configureFileHandler(config.file, errorManager, cleanupFiler));
    }
    if (config.syslog.enable) {
        final Handler syslogHandler = configureSyslogHandler(config.syslog, errorManager, cleanupFiler);
        if (syslogHandler != null) {
            handlers.add(syslogHandler);
        }
    }
    if ((launchMode.isDevOrTest() || enableWebStream) && devUiConsoleHandler != null && devUiConsoleHandler.getValue().isPresent()) {
        Handler handler = devUiConsoleHandler.getValue().get();
        handler.setErrorManager(errorManager);
        handler.setFilter(new LogCleanupFilter(filterElements));
        if (possibleBannerSupplier != null && possibleBannerSupplier.getValue().isPresent()) {
            Supplier<String> bannerSupplier = possibleBannerSupplier.getValue().get();
            String header = "\n" + bannerSupplier.get();
            handler.publish(new LogRecord(Level.INFO, header));
        }
        handlers.add(handler);
    }
    if (!categories.isEmpty()) {
        Map<String, Handler> namedHandlers = createNamedHandlers(config, consoleRuntimeConfig.getValue(), possibleFormatters, errorManager, cleanupFiler, launchMode);
        Map<String, Handler> additionalNamedHandlersMap;
        if (additionalNamedHandlers.isEmpty()) {
            additionalNamedHandlersMap = Collections.emptyMap();
        } else {
            additionalNamedHandlersMap = new HashMap<>();
            for (RuntimeValue<Map<String, Handler>> runtimeValue : additionalNamedHandlers) {
                runtimeValue.getValue().forEach(new AdditionalNamedHandlersConsumer(additionalNamedHandlersMap, errorManager, filterElements));
            }
        }
        namedHandlers.putAll(additionalNamedHandlersMap);
        categories.forEach(new BiConsumer<String, CategoryConfig>() {

            @Override
            public void accept(String categoryName, CategoryConfig config) {
                final Level logLevel = getLogLevel(categoryName, categories, CategoryConfig::getLevel, buildConfig.minLevel);
                final Level minLogLevel = getLogLevel(categoryName, buildConfig.categories, CategoryBuildTimeConfig::getMinLevel, buildConfig.minLevel);
                if (logLevel.intValue() < minLogLevel.intValue()) {
                    log.warnf("Log level %s for category '%s' set below minimum logging level %s, promoting it to %s", logLevel, categoryName, minLogLevel, minLogLevel);
                    config.level = InheritableLevel.of(minLogLevel.toString());
                }
            }
        });
        categories.forEach(new CategoryLoggerConsumer(logContext, namedHandlers, errorManager));
    }
    for (RuntimeValue<Optional<Handler>> additionalHandler : additionalHandlers) {
        final Optional<Handler> optional = additionalHandler.getValue();
        if (optional.isPresent()) {
            final Handler handler = optional.get();
            handler.setErrorManager(errorManager);
            handler.setFilter(cleanupFiler);
            handlers.add(handler);
        }
    }
    InitialConfigurator.DELAYED_HANDLER.setAutoFlush(false);
    InitialConfigurator.DELAYED_HANDLER.setHandlers(handlers.toArray(EmbeddedConfigurator.NO_HANDLERS));
}
Also used : OnlyOnceErrorManager(org.jboss.logmanager.errormanager.OnlyOnceErrorManager) ErrorManager(java.util.logging.ErrorManager) ArrayList(java.util.ArrayList) Logger(org.jboss.logmanager.Logger) OnlyOnceErrorManager(org.jboss.logmanager.errormanager.OnlyOnceErrorManager) LogRecord(java.util.logging.LogRecord) Optional(java.util.Optional) LogContext(org.jboss.logmanager.LogContext) SyslogHandler(org.jboss.logmanager.handlers.SyslogHandler) FileHandler(org.jboss.logmanager.handlers.FileHandler) PeriodicSizeRotatingFileHandler(org.jboss.logmanager.handlers.PeriodicSizeRotatingFileHandler) ConsoleHandler(org.jboss.logmanager.handlers.ConsoleHandler) SizeRotatingFileHandler(org.jboss.logmanager.handlers.SizeRotatingFileHandler) Handler(java.util.logging.Handler) AsyncHandler(org.jboss.logmanager.handlers.AsyncHandler) Level(java.util.logging.Level) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Logger (org.jboss.logmanager.Logger)11 LogContext (org.jboss.logmanager.LogContext)6 Path (java.nio.file.Path)3 Handler (java.util.logging.Handler)3 Level (java.util.logging.Level)3 ModelNode (org.jboss.dmr.ModelNode)3 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ErrorManager (java.util.logging.ErrorManager)2 LoggingLogger (org.jboss.as.logging.logging.LoggingLogger)2 Configurator (org.jboss.logmanager.Configurator)2 PropertyConfigurator (org.jboss.logmanager.PropertyConfigurator)2 OnlyOnceErrorManager (org.jboss.logmanager.errormanager.OnlyOnceErrorManager)2 AsyncHandler (org.jboss.logmanager.handlers.AsyncHandler)2 ConsoleHandler (org.jboss.logmanager.handlers.ConsoleHandler)2 FileHandler (org.jboss.logmanager.handlers.FileHandler)2 PeriodicSizeRotatingFileHandler (org.jboss.logmanager.handlers.PeriodicSizeRotatingFileHandler)2 SizeRotatingFileHandler (org.jboss.logmanager.handlers.SizeRotatingFileHandler)2 SyslogHandler (org.jboss.logmanager.handlers.SyslogHandler)2