Search in sources :

Example 1 with JavaLogService

use of liquibase.logging.core.JavaLogService in project liquibase by liquibase.

the class LiquibaseCommandLine method configureLogging.

private void configureLogging(Level logLevel, File logFile) throws IOException {
    configuredLogLevel = logLevel;
    System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] %4$s [%2$s] %5$s%6$s%n");
    java.util.logging.Logger liquibaseLogger = java.util.logging.Logger.getLogger("liquibase");
    final JavaLogService logService = (JavaLogService) Scope.getCurrentScope().get(Scope.Attr.logService, LogService.class);
    logService.setParent(liquibaseLogger);
    java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger("");
    Level cliLogLevel = logLevel;
    if (logFile != null) {
        if (fileHandler == null) {
            fileHandler = new FileHandler(logFile.getAbsolutePath(), true);
            fileHandler.setFormatter(new SimpleFormatter());
            rootLogger.addHandler(fileHandler);
        }
        fileHandler.setLevel(logLevel);
        if (logLevel == Level.OFF) {
            fileHandler.setLevel(Level.FINE);
        }
        cliLogLevel = Level.OFF;
    }
    rootLogger.setLevel(logLevel);
    liquibaseLogger.setLevel(logLevel);
    for (Handler handler : rootLogger.getHandlers()) {
        if (handler instanceof ConsoleHandler) {
            handler.setLevel(cliLogLevel);
        }
        handler.setFilter(new SecureLogFilter(logService.getFilter()));
    }
}
Also used : java.util.logging(java.util.logging) JavaLogService(liquibase.logging.core.JavaLogService) LogService(liquibase.logging.LogService) JavaLogService(liquibase.logging.core.JavaLogService)

Example 2 with JavaLogService

use of liquibase.logging.core.JavaLogService in project liquibase by liquibase.

the class Scope method getCurrentScope.

public static Scope getCurrentScope() {
    if (scopeManager == null) {
        scopeManager = new SingletonScopeManager();
    }
    if (scopeManager.getCurrentScope() == null) {
        Scope rootScope = new Scope();
        scopeManager.setCurrentScope(rootScope);
        rootScope.values.put(Attr.logService.name(), new JavaLogService());
        rootScope.values.put(Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor());
        rootScope.values.put(Attr.serviceLocator.name(), new StandardServiceLocator());
        rootScope.values.put(Attr.ui.name(), new ConsoleUIService());
        rootScope.getSingleton(LiquibaseConfiguration.class).init(rootScope);
        LogService overrideLogService = rootScope.getSingleton(LogServiceFactory.class).getDefaultLogService();
        if (overrideLogService == null) {
            throw new UnexpectedLiquibaseException("Cannot find default log service");
        }
        rootScope.values.put(Attr.logService.name(), overrideLogService);
        // check for higher-priority serviceLocator
        ServiceLocator serviceLocator = rootScope.getServiceLocator();
        for (ServiceLocator possibleLocator : serviceLocator.findInstances(ServiceLocator.class)) {
            if (possibleLocator.getPriority() > serviceLocator.getPriority()) {
                serviceLocator = possibleLocator;
            }
        }
        rootScope.values.put(Attr.serviceLocator.name(), serviceLocator);
        rootScope.values.put(Attr.osgiPlatform.name(), Activator.OSGIContainerChecker.isOsgiPlatform());
    }
    return scopeManager.getCurrentScope();
}
Also used : StandardServiceLocator(liquibase.servicelocator.StandardServiceLocator) ServiceLocator(liquibase.servicelocator.ServiceLocator) ConsoleUIService(liquibase.ui.ConsoleUIService) StandardServiceLocator(liquibase.servicelocator.StandardServiceLocator) JavaLogService(liquibase.logging.core.JavaLogService) LiquibaseConfiguration(liquibase.configuration.LiquibaseConfiguration) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor) LogServiceFactory(liquibase.logging.core.LogServiceFactory) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) LogService(liquibase.logging.LogService) JavaLogService(liquibase.logging.core.JavaLogService)

Example 3 with JavaLogService

use of liquibase.logging.core.JavaLogService in project liquibase by liquibase.

the class Main method run.

/**
 * Process the command line arguments and perform the appropriate main action (update, rollback etc.)
 *
 * @param args the command line arguments
 * @return the errorlevel to be returned to the operating system, e.g. for further processing by scripts
 * @throws LiquibaseException a runtime exception
 */
public static int run(String[] args) throws Exception {
    Map<String, Object> scopeObjects = new HashMap<>();
    final IntegrationDetails integrationDetails = new IntegrationDetails();
    integrationDetails.setName("cli");
    final ListIterator<String> argIterator = Arrays.asList(args).listIterator();
    while (argIterator.hasNext()) {
        final String arg = argIterator.next();
        if (arg.startsWith("--")) {
            if (arg.contains("=")) {
                String[] splitArg = arg.split("=", 2);
                String argKey = "argument__" + splitArg[0].replaceFirst("^--", "");
                if (splitArg.length == 2) {
                    integrationDetails.setParameter(argKey, splitArg[1]);
                } else {
                    integrationDetails.setParameter(argKey, "true");
                }
            } else {
                String argKey = "argument__" + arg.replaceFirst("^--", "");
                if (argIterator.hasNext()) {
                    final String next = argIterator.next();
                    if (next.startsWith("--") || isCommand(next)) {
                        integrationDetails.setParameter(argKey, "true");
                        // put value back
                        argIterator.previous();
                    } else {
                        integrationDetails.setParameter(argKey, next);
                    }
                } else {
                    integrationDetails.setParameter(argKey, "true");
                }
            }
        }
    }
    scopeObjects.put("integrationDetails", integrationDetails);
    if (!Main.runningFromNewCli) {
        ConsoleUIService ui = new ConsoleUIService();
        ui.setAllowPrompt(true);
        scopeObjects.put(Scope.Attr.ui.name(), ui);
    }
    return Scope.child(scopeObjects, new Scope.ScopedRunnerWithReturn<Integer>() {

        @Override
        public Integer run() throws Exception {
            Main main = new Main();
            try {
                if ((args.length == 0) || ((args.length == 1) && ("--" + OPTIONS.HELP).equals(args[0]))) {
                    main.printHelp(outputStream);
                    return Integer.valueOf(0);
                } else if (("--" + OPTIONS.VERSION).equals(args[0])) {
                    main.command = "";
                    main.parseDefaultPropertyFiles();
                    Scope.getCurrentScope().getUI().sendMessage(CommandLineUtils.getBanner());
                    Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("version.number"), LiquibaseUtil.getBuildVersionInfo()));
                    LicenseService licenseService = Scope.getCurrentScope().getSingleton(LicenseServiceFactory.class).getLicenseService();
                    if (licenseService != null && main.liquibaseProLicenseKey != null) {
                        Location licenseKeyLocation = new Location("property liquibaseProLicenseKey", LocationType.BASE64_STRING, main.liquibaseProLicenseKey);
                        LicenseInstallResult result = licenseService.installLicense(licenseKeyLocation);
                        if (result.code != 0) {
                            String allMessages = String.join("\n", result.messages);
                            Scope.getCurrentScope().getUI().sendErrorMessage(allMessages);
                        }
                    }
                    if (licenseService != null) {
                        Scope.getCurrentScope().getUI().sendMessage(licenseService.getLicenseInfo());
                    }
                    Scope.getCurrentScope().getUI().sendMessage(String.format("Running Java under %s (Version %s)", System.getProperties().getProperty("java.home"), System.getProperty("java.version")));
                    return Integer.valueOf(0);
                }
                // 
                for (int i = 0; i < args.length; i++) {
                    CodePointCheck codePointCheck = checkArg(args[i]);
                    if (codePointCheck != null) {
                        String message = "A non-standard character '" + codePointCheck.ch + "' was detected on the command line at position " + (codePointCheck.position + 1) + " of argument number " + (i + 1) + ".\nIf problems occur, please remove the character and try again.";
                        LOG.warning(message);
                        System.err.println(message);
                    }
                }
                try {
                    main.parseOptions(args);
                    if (main.command == null) {
                        main.printHelp(outputStream);
                        return Integer.valueOf(0);
                    }
                } catch (CommandLineParsingException e) {
                    Scope.getCurrentScope().getUI().sendMessage(CommandLineUtils.getBanner());
                    Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("how.to.display.help"));
                    throw e;
                }
                if (!Main.runningFromNewCli) {
                    final ConsoleUIService ui = (ConsoleUIService) Scope.getCurrentScope().getUI();
                    System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tF %1$tT] %4$s [%2$s] %5$s%6$s%n");
                    java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger("");
                    java.util.logging.Logger liquibaseLogger = java.util.logging.Logger.getLogger("liquibase");
                    liquibaseLogger.setParent(rootLogger);
                    final JavaLogService logService = (JavaLogService) Scope.getCurrentScope().get(Scope.Attr.logService, LogService.class);
                    logService.setParent(liquibaseLogger);
                    if (main.logLevel == null) {
                        String defaultLogLevel = System.getProperty("liquibase.log.level");
                        if (defaultLogLevel == null) {
                            setLogLevel(logService, rootLogger, liquibaseLogger, Level.OFF);
                        } else {
                            setLogLevel(logService, rootLogger, liquibaseLogger, parseLogLevel(defaultLogLevel, ui));
                        }
                    } else {
                        setLogLevel(logService, rootLogger, liquibaseLogger, parseLogLevel(main.logLevel, ui));
                    }
                    if (main.logFile != null) {
                        FileHandler fileHandler = new FileHandler(main.logFile, true);
                        fileHandler.setFormatter(new SimpleFormatter());
                        if (liquibaseLogger.getLevel() == Level.OFF) {
                            fileHandler.setLevel(Level.FINE);
                        }
                        rootLogger.addHandler(fileHandler);
                        for (Handler handler : rootLogger.getHandlers()) {
                            if (handler instanceof ConsoleHandler) {
                                handler.setLevel(Level.OFF);
                            }
                        }
                    }
                    if (main.command != null && main.command.toLowerCase().endsWith("sql")) {
                        ui.setOutputStream(System.err);
                    }
                }
                LicenseService licenseService = Scope.getCurrentScope().getSingleton(LicenseServiceFactory.class).getLicenseService();
                if (licenseService != null) {
                    if (main.liquibaseProLicenseKey == null) {
                        if (!Main.runningFromNewCli) {
                            Scope.getCurrentScope().getLog(getClass()).info("No Liquibase Pro license key supplied. Please set liquibaseProLicenseKey on command line or in liquibase.properties to use Liquibase Pro features.");
                        }
                    } else {
                        Location licenseKeyLocation = new Location("property liquibaseProLicenseKey", LocationType.BASE64_STRING, main.liquibaseProLicenseKey);
                        LicenseInstallResult result = licenseService.installLicense(licenseKeyLocation);
                        if (result.code != 0) {
                            String allMessages = String.join("\n", result.messages);
                            if (!Main.runningFromNewCli) {
                                Scope.getCurrentScope().getUI().sendMessage(allMessages);
                            }
                        } else {
                            main.liquibaseProLicenseValid = true;
                        }
                    }
                    // 
                    if (licenseService.daysTilExpiration() < 0) {
                        main.liquibaseProLicenseValid = false;
                    }
                    if (!Main.runningFromNewCli) {
                        Scope.getCurrentScope().getUI().sendMessage(licenseService.getLicenseInfo());
                    }
                }
                if (!Main.runningFromNewCli) {
                    Scope.getCurrentScope().getUI().sendMessage(CommandLineUtils.getBanner());
                }
                if (!LiquibaseCommandLineConfiguration.SHOULD_RUN.getCurrentValue()) {
                    Scope.getCurrentScope().getUI().sendErrorMessage((String.format(coreBundle.getString("did.not.run.because.param.was.set.to.false"), LiquibaseCommandLineConfiguration.SHOULD_RUN.getCurrentConfiguredValue().getProvidedValue().getActualKey())));
                    return Integer.valueOf(0);
                }
                if (setupNeeded(main)) {
                    List<String> setupMessages = main.checkSetup();
                    if (!setupMessages.isEmpty()) {
                        main.printHelp(setupMessages, isStandardOutputRequired(main.command) ? System.err : outputStream);
                        return Integer.valueOf(1);
                    }
                }
                // 
                if (StringUtil.isNotEmpty(main.liquibaseHubApiKey)) {
                    DeprecatedConfigurationValueProvider.setData(HubConfiguration.LIQUIBASE_HUB_API_KEY, main.liquibaseHubApiKey);
                }
                // 
                if (StringUtil.isNotEmpty(main.liquibaseHubUrl)) {
                    DeprecatedConfigurationValueProvider.setData(HubConfiguration.LIQUIBASE_HUB_URL, main.liquibaseHubUrl);
                }
                main.applyDefaults();
                Map<String, Object> innerScopeObjects = new HashMap<>();
                innerScopeObjects.put("defaultsFile", LiquibaseCommandLineConfiguration.DEFAULTS_FILE.getCurrentValue());
                if (!Main.runningFromNewCli) {
                    innerScopeObjects.put(Scope.Attr.resourceAccessor.name(), new ClassLoaderResourceAccessor(main.configureClassLoader()));
                }
                Scope.child(innerScopeObjects, () -> {
                    main.doMigration();
                    if (!Main.runningFromNewCli) {
                        if (COMMANDS.UPDATE.equals(main.command)) {
                            Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("update.successful"));
                        } else if (main.command.startsWith(COMMANDS.ROLLBACK)) {
                            Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("rollback.successful"));
                        } else {
                            Scope.getCurrentScope().getUI().sendMessage(String.format(coreBundle.getString("command.successful"), main.command));
                        }
                    }
                });
            } catch (Throwable e) {
                String message = e.getMessage();
                if (e.getCause() != null) {
                    message = e.getCause().getMessage();
                }
                if (message == null) {
                    message = coreBundle.getString("unknown.reason");
                }
                // trace because the logger already did that upstream.
                try {
                    if (e.getCause() instanceof ValidationFailedException) {
                        ((ValidationFailedException) e.getCause()).printDescriptiveError(outputStream);
                    } else {
                        if (!Main.runningFromNewCli) {
                            if (main.outputsLogMessages) {
                                Scope.getCurrentScope().getUI().sendErrorMessage((String.format(coreBundle.getString("unexpected.error"), message)), e);
                            } else {
                                Scope.getCurrentScope().getUI().sendMessage((String.format(coreBundle.getString("unexpected.error"), message)));
                                Scope.getCurrentScope().getUI().sendMessage(coreBundle.getString("for.more.information.use.loglevel.flag"));
                                // send it to the LOG in case we're using logFile
                                Scope.getCurrentScope().getLog(getClass()).severe((String.format(coreBundle.getString("unexpected.error"), message)), e);
                            }
                        }
                    }
                } catch (IllegalFormatException e1) {
                    if (Main.runningFromNewCli) {
                        throw e1;
                    }
                    e1.printStackTrace();
                }
                throw new LiquibaseException(String.format(coreBundle.getString("unexpected.error"), message), e);
            }
            if (isHubEnabled(main.command) && HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue() != null && !Scope.getCurrentScope().getSingleton(HubServiceFactory.class).isOnline()) {
                Scope.getCurrentScope().getUI().sendMessage("WARNING: The command " + main.command + " operations were not synced with your Liquibase Hub account because: " + StringUtil.lowerCaseFirst(Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getOfflineReason()));
            }
            return Integer.valueOf(0);
        }
    });
}
Also used : IntegrationDetails(liquibase.integration.IntegrationDetails) Logger(liquibase.logging.Logger) JavaLogService(liquibase.logging.core.JavaLogService) HubServiceFactory(liquibase.hub.HubServiceFactory) ParseException(java.text.ParseException) CommandFailedException(liquibase.command.CommandFailedException) MalformedURLException(java.net.MalformedURLException) CommandScope(liquibase.command.CommandScope) java.util(java.util) ConsoleUIService(liquibase.ui.ConsoleUIService) ClassLoaderResourceAccessor(liquibase.resource.ClassLoaderResourceAccessor)

Aggregations

JavaLogService (liquibase.logging.core.JavaLogService)3 LogService (liquibase.logging.LogService)2 ClassLoaderResourceAccessor (liquibase.resource.ClassLoaderResourceAccessor)2 ConsoleUIService (liquibase.ui.ConsoleUIService)2 MalformedURLException (java.net.MalformedURLException)1 ParseException (java.text.ParseException)1 java.util (java.util)1 java.util.logging (java.util.logging)1 CommandFailedException (liquibase.command.CommandFailedException)1 CommandScope (liquibase.command.CommandScope)1 LiquibaseConfiguration (liquibase.configuration.LiquibaseConfiguration)1 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)1 HubServiceFactory (liquibase.hub.HubServiceFactory)1 IntegrationDetails (liquibase.integration.IntegrationDetails)1 Logger (liquibase.logging.Logger)1 LogServiceFactory (liquibase.logging.core.LogServiceFactory)1 ServiceLocator (liquibase.servicelocator.ServiceLocator)1 StandardServiceLocator (liquibase.servicelocator.StandardServiceLocator)1