Search in sources :

Example 1 with ColorPatternFormatter

use of org.jboss.logmanager.formatters.ColorPatternFormatter in project quarkus-test-framework by quarkus-qe.

the class Log method configure.

public static void configure(ScenarioContext scenario) {
    // Configure Log Manager
    try (InputStream in = QuarkusScenarioBootstrap.class.getResourceAsStream("/logging.properties")) {
        LogManager.getLogManager().readConfiguration(in);
    } catch (IOException e) {
    // ignore
    }
    String logPattern = LOG_FORMAT.get();
    Level level = Level.parse(LOG_LEVEL.get());
    // Configure logger handlers
    Logger logger = LogManager.getLogManager().getLogger("");
    logger.setLevel(level);
    // - Console
    ConsoleHandler console = new ConsoleHandler(ConsoleHandler.Target.SYSTEM_OUT, NOCOLOR ? new PatternFormatter(logPattern) : new ColorPatternFormatter(logPattern));
    console.setLevel(level);
    logger.addHandler(console);
    // - File
    try {
        FileHandler file = new FileHandler(new PatternFormatter(logPattern), scenario.getLogFile().toFile());
        file.setLevel(level);
        logger.addHandler(file);
    } catch (Exception ex) {
        Log.warn("Could not configure file handler. Caused by " + ex);
    }
}
Also used : InputStream(java.io.InputStream) ColorPatternFormatter(org.jboss.logmanager.formatters.ColorPatternFormatter) Level(java.util.logging.Level) PatternFormatter(org.jboss.logmanager.formatters.PatternFormatter) ColorPatternFormatter(org.jboss.logmanager.formatters.ColorPatternFormatter) IOException(java.io.IOException) Logger(java.util.logging.Logger) ConsoleHandler(org.jboss.logmanager.handlers.ConsoleHandler) IOException(java.io.IOException) FileHandler(org.jboss.logmanager.handlers.FileHandler)

Example 2 with ColorPatternFormatter

use of org.jboss.logmanager.formatters.ColorPatternFormatter in project quarkus by quarkusio.

the class IsolatedDevModeMain method firstStart.

private synchronized void firstStart(QuarkusClassLoader deploymentClassLoader, List<CodeGenData> codeGens) {
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    try {
        // ok, we have resolved all the deps
        try {
            StartupAction start = augmentAction.createInitialRuntimeApplication();
            // this is a bit yuck, but we need replace the default
            // exit handler in the runtime class loader
            // TODO: look at implementing a common core classloader, that removes the need for this sort of crappy hack
            curatedApplication.getBaseRuntimeClassLoader().loadClass(ApplicationLifecycleManager.class.getName()).getMethod("setDefaultExitCodeHandler", Consumer.class).invoke(null, new Consumer<Integer>() {

                @Override
                public void accept(Integer integer) {
                    if (restarting || ApplicationLifecycleManager.isVmShuttingDown() || context.isAbortOnFailedStart() || context.isTest()) {
                        return;
                    }
                    if (consoleContext == null) {
                        consoleContext = ConsoleStateManager.INSTANCE.createContext("Completed Application");
                    }
                    // this sucks, but when we get here logging is gone
                    // so we just setup basic console logging
                    InitialConfigurator.DELAYED_HANDLER.addHandler(new ConsoleHandler(ConsoleHandler.Target.SYSTEM_OUT, new ColorPatternFormatter("%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c{3.}] (%t) %s%e%n")));
                    consoleContext.reset(new ConsoleCommand(' ', "Restarts the application", "to restart", 0, null, () -> {
                        consoleContext.reset();
                        RuntimeUpdatesProcessor.INSTANCE.doScan(true, true);
                    }), new ConsoleCommand('e', "Edits the command line parameters and restarts", "to edit command line args (currently '" + MessageFormat.GREEN + String.join(" ", context.getArgs()) + MessageFormat.RESET + "')", 100, new ConsoleCommand.HelpState(() -> BLUE, () -> String.join(" ", context.getArgs())), new Consumer<String>() {

                        @Override
                        public void accept(String args) {
                            try {
                                context.setArgs(CommandLineUtils.translateCommandline(args));
                            } catch (CommandLineException e) {
                                log.error("Failed to parse command line", e);
                                return;
                            }
                            consoleContext.reset();
                            RuntimeUpdatesProcessor.INSTANCE.doScan(true, true);
                        }
                    }));
                }
            });
            startCodeGenWatcher(deploymentClassLoader, codeGens, context.getBuildSystemProperties());
            runner = start.runMainClass(context.getArgs());
            RuntimeUpdatesProcessor.INSTANCE.setConfiguredInstrumentationEnabled(runner.getConfigValue("quarkus.live-reload.instrumentation", Boolean.class).orElse(false));
            firstStartCompleted = true;
            for (DevModeListener listener : ServiceLoader.load(DevModeListener.class)) {
                listeners.add(listener);
            }
            listeners.sort(Comparator.comparingInt(DevModeListener::order));
            for (DevModeListener listener : ServiceLoader.load(DevModeListener.class)) {
                try {
                    listener.afterFirstStart(runner);
                } catch (Exception e) {
                    log.warn("Unable to invoke 'afterFirstStart' of " + listener.getClass(), e);
                }
            }
        } catch (Throwable t) {
            Throwable rootCause = t;
            while (rootCause.getCause() != null) {
                rootCause = rootCause.getCause();
            }
            if (!(rootCause instanceof BindException)) {
                deploymentProblem = t;
                if (!context.isAbortOnFailedStart()) {
                    // we need to set this here, while we still have the correct TCCL
                    // this is so the config is still valid, and we can read HTTP config from application.properties
                    log.info("Attempting to start live reload endpoint to recover from previous Quarkus startup failure");
                    if (RuntimeUpdatesProcessor.INSTANCE != null) {
                        Thread.currentThread().setContextClassLoader(curatedApplication.getBaseRuntimeClassLoader());
                        try {
                            if (!InitialConfigurator.DELAYED_HANDLER.isActivated()) {
                                Class<?> cl = Thread.currentThread().getContextClassLoader().loadClass(LoggingSetupRecorder.class.getName());
                                cl.getMethod("handleFailedStart").invoke(null);
                            }
                            RuntimeUpdatesProcessor.INSTANCE.startupFailed();
                            // this exception has already been logged, so don't log it again
                            if (!(t instanceof ApplicationStartException)) {
                                log.error("Failed to start quarkus", t);
                            }
                        } catch (Exception e) {
                            close();
                            log.error("Failed to start quarkus", t);
                            log.error("Failed to recover after failed start", e);
                            // this is the end of the road, we just exit
                            // generally we only hit this if something is already listening on the HTTP port
                            // or the system config is so broken we can't start HTTP
                            System.exit(1);
                        }
                    }
                } else {
                    log.error("Failed to start quarkus", t);
                }
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}
Also used : ApplicationLifecycleManager(io.quarkus.runtime.ApplicationLifecycleManager) StartupAction(io.quarkus.bootstrap.app.StartupAction) ColorPatternFormatter(org.jboss.logmanager.formatters.ColorPatternFormatter) BindException(java.net.BindException) ApplicationStartException(io.quarkus.dev.appstate.ApplicationStartException) ConsoleCommand(io.quarkus.deployment.console.ConsoleCommand) ConsoleHandler(org.jboss.logmanager.handlers.ConsoleHandler) CommandLineException(org.apache.maven.shared.utils.cli.CommandLineException) BindException(java.net.BindException) ApplicationStartException(io.quarkus.dev.appstate.ApplicationStartException) CommandLineException(org.apache.maven.shared.utils.cli.CommandLineException) IOException(java.io.IOException) BiConsumer(java.util.function.BiConsumer) Consumer(java.util.function.Consumer) QuarkusClassLoader(io.quarkus.bootstrap.classloading.QuarkusClassLoader)

Example 3 with ColorPatternFormatter

use of org.jboss.logmanager.formatters.ColorPatternFormatter in project quarkus by quarkusio.

the class LoggingSetupRecorder method configureConsoleHandler.

private static Handler configureConsoleHandler(final ConsoleConfig config, ConsoleRuntimeConfig consoleRuntimeConfig, final ErrorManager defaultErrorManager, final LogCleanupFilter cleanupFilter, final List<RuntimeValue<Optional<Formatter>>> possibleFormatters, final RuntimeValue<Optional<Supplier<String>>> possibleBannerSupplier, LaunchMode launchMode) {
    Formatter formatter = null;
    boolean formatterWarning = false;
    for (RuntimeValue<Optional<Formatter>> value : possibleFormatters) {
        if (formatter != null) {
            formatterWarning = true;
        }
        final Optional<Formatter> val = value.getValue();
        if (val.isPresent()) {
            formatter = val.get();
        }
    }
    boolean color = false;
    if (formatter == null) {
        Supplier<String> bannerSupplier = null;
        if (possibleBannerSupplier != null && possibleBannerSupplier.getValue().isPresent()) {
            bannerSupplier = possibleBannerSupplier.getValue().get();
        }
        if (ColorSupport.isColorEnabled(consoleRuntimeConfig, config)) {
            color = true;
            ColorPatternFormatter colorPatternFormatter = new ColorPatternFormatter(config.darken, config.format);
            if (bannerSupplier != null) {
                formatter = new BannerFormatter(colorPatternFormatter, true, bannerSupplier);
            } else {
                formatter = colorPatternFormatter;
            }
        } else {
            PatternFormatter patternFormatter = new PatternFormatter(config.format);
            if (bannerSupplier != null) {
                formatter = new BannerFormatter(patternFormatter, false, bannerSupplier);
            } else {
                formatter = patternFormatter;
            }
        }
    }
    final ConsoleHandler consoleHandler = new ConsoleHandler(config.stderr ? ConsoleHandler.Target.SYSTEM_ERR : ConsoleHandler.Target.SYSTEM_OUT, formatter);
    consoleHandler.setLevel(config.level);
    consoleHandler.setErrorManager(defaultErrorManager);
    consoleHandler.setFilter(cleanupFilter);
    Handler handler = config.async.enable ? createAsyncHandler(config.async, config.level, consoleHandler) : consoleHandler;
    if (color && launchMode.isDevOrTest() && !config.async.enable) {
        final Handler delegate = handler;
        handler = new Handler() {

            @Override
            public void publish(LogRecord record) {
                BiConsumer<LogRecord, Consumer<LogRecord>> formatter = CurrentAppExceptionHighlighter.THROWABLE_FORMATTER;
                if (formatter != null) {
                    formatter.accept(record, delegate::publish);
                } else {
                    delegate.publish(record);
                }
            }

            @Override
            public void flush() {
                delegate.flush();
            }

            @Override
            public void close() throws SecurityException {
                delegate.close();
            }
        };
    }
    if (formatterWarning) {
        handler.getErrorManager().error("Multiple formatters were activated", null, ErrorManager.GENERIC_FAILURE);
    }
    return handler;
}
Also used : Optional(java.util.Optional) PatternFormatter(org.jboss.logmanager.formatters.PatternFormatter) Formatter(java.util.logging.Formatter) ColorPatternFormatter(org.jboss.logmanager.formatters.ColorPatternFormatter) ColorPatternFormatter(org.jboss.logmanager.formatters.ColorPatternFormatter) 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) ConsoleHandler(org.jboss.logmanager.handlers.ConsoleHandler) LogRecord(java.util.logging.LogRecord) PatternFormatter(org.jboss.logmanager.formatters.PatternFormatter) ColorPatternFormatter(org.jboss.logmanager.formatters.ColorPatternFormatter) BiConsumer(java.util.function.BiConsumer)

Aggregations

ColorPatternFormatter (org.jboss.logmanager.formatters.ColorPatternFormatter)3 ConsoleHandler (org.jboss.logmanager.handlers.ConsoleHandler)3 IOException (java.io.IOException)2 BiConsumer (java.util.function.BiConsumer)2 PatternFormatter (org.jboss.logmanager.formatters.PatternFormatter)2 FileHandler (org.jboss.logmanager.handlers.FileHandler)2 StartupAction (io.quarkus.bootstrap.app.StartupAction)1 QuarkusClassLoader (io.quarkus.bootstrap.classloading.QuarkusClassLoader)1 ConsoleCommand (io.quarkus.deployment.console.ConsoleCommand)1 ApplicationStartException (io.quarkus.dev.appstate.ApplicationStartException)1 ApplicationLifecycleManager (io.quarkus.runtime.ApplicationLifecycleManager)1 InputStream (java.io.InputStream)1 BindException (java.net.BindException)1 Optional (java.util.Optional)1 Consumer (java.util.function.Consumer)1 Formatter (java.util.logging.Formatter)1 Handler (java.util.logging.Handler)1 Level (java.util.logging.Level)1 LogRecord (java.util.logging.LogRecord)1 Logger (java.util.logging.Logger)1