Search in sources :

Example 41 with Formatter

use of java.util.logging.Formatter in project guava by google.

the class ServiceManagerTest method testEmptyServiceManager.

/**
 * This is for covering a case where the ServiceManager would behave strangely if constructed with
 * no service under management. Listeners would never fire because the ServiceManager was healthy
 * and stopped at the same time. This test ensures that listeners fire and isHealthy makes sense.
 */
public void testEmptyServiceManager() {
    Logger logger = Logger.getLogger(ServiceManager.class.getName());
    logger.setLevel(Level.FINEST);
    TestLogHandler logHandler = new TestLogHandler();
    logger.addHandler(logHandler);
    ServiceManager manager = new ServiceManager(Arrays.<Service>asList());
    RecordingListener listener = new RecordingListener();
    manager.addListener(listener, directExecutor());
    manager.startAsync().awaitHealthy();
    assertTrue(manager.isHealthy());
    assertTrue(listener.healthyCalled);
    assertFalse(listener.stoppedCalled);
    assertTrue(listener.failedServices.isEmpty());
    manager.stopAsync().awaitStopped();
    assertFalse(manager.isHealthy());
    assertTrue(listener.stoppedCalled);
    assertTrue(listener.failedServices.isEmpty());
    // check that our NoOpService is not directly observable via any of the inspection methods or
    // via logging.
    assertEquals("ServiceManager{services=[]}", manager.toString());
    assertTrue(manager.servicesByState().isEmpty());
    assertTrue(manager.startupTimes().isEmpty());
    Formatter logFormatter = new Formatter() {

        @Override
        public String format(LogRecord record) {
            return formatMessage(record);
        }
    };
    for (LogRecord record : logHandler.getStoredLogRecords()) {
        assertThat(logFormatter.format(record)).doesNotContain("NoOpService");
    }
}
Also used : TestLogHandler(com.google.common.testing.TestLogHandler) LogRecord(java.util.logging.LogRecord) Formatter(java.util.logging.Formatter) Logger(java.util.logging.Logger)

Example 42 with Formatter

use of java.util.logging.Formatter in project 360-Engine-for-Android by 360.

the class LogUtils method enableLogcat.

/**
 * Enable logging.
 */
public static void enableLogcat() {
    mEnabled = true;
    /**
     * Enable the SD Card logger *
     */
    sLogger = Logger.getLogger(APP_NAME_PREFIX);
    try {
        FileHandler fileHandler = new FileHandler(APP_FILE_NAME, LOG_FILE_LIMIT, LOG_FILE_COUNT);
        fileHandler.setFormatter(new Formatter() {

            @Override
            public String format(final LogRecord logRecord) {
                StringBuilder sb = new StringBuilder();
                sb.append(DATE_FORMAT.format(new Date(logRecord.getMillis())));
                sb.append(" ");
                sb.append(logRecord.getMessage());
                sb.append("\n");
                return sb.toString();
            }
        });
        sLogger.addHandler(fileHandler);
    } catch (IOException e) {
        logE("LogUtils.logToFile() IOException, data will not be logged " + "to file", e);
        sLogger = null;
    }
    if (Settings.ENABLED_PROFILE_ENGINES) {
        /**
         * Enable the SD Card profiler *
         */
        sProfileLogger = Logger.getLogger("profiler");
        try {
            FileHandler fileHandler = new FileHandler("/sdcard/engineprofiler.log", LOG_FILE_LIMIT, LOG_FILE_COUNT);
            fileHandler.setFormatter(new Formatter() {

                @Override
                public String format(final LogRecord logRecord) {
                    StringBuilder sb = new StringBuilder();
                    sb.append(DATE_FORMAT.format(new Date(logRecord.getMillis())));
                    sb.append("|");
                    sb.append(logRecord.getMessage());
                    sb.append("\n");
                    return sb.toString();
                }
            });
            sProfileLogger.addHandler(fileHandler);
        } catch (IOException e) {
            logE("LogUtils.logToFile() IOException, data will not be logged " + "to file", e);
            sProfileLogger = null;
        }
    }
}
Also used : LogRecord(java.util.logging.LogRecord) Formatter(java.util.logging.Formatter) IOException(java.io.IOException) Date(java.util.Date) FileHandler(java.util.logging.FileHandler)

Example 43 with Formatter

use of java.util.logging.Formatter in project ignite by apache.

the class CommandHandler method execute.

/**
 * Parse and execute command.
 *
 * @param rawArgs Arguments to parse and execute.
 * @return Exit code.
 */
public int execute(List<String> rawArgs) {
    LocalDateTime startTime = LocalDateTime.now();
    Thread.currentThread().setName("session=" + ses);
    logger.info("Control utility [ver. " + ACK_VER_STR + "]");
    logger.info(COPYRIGHT);
    logger.info("User: " + System.getProperty("user.name"));
    logger.info("Time: " + startTime.format(formatter));
    String commandName = "";
    Throwable err = null;
    boolean verbose = false;
    try {
        if (isHelp(rawArgs)) {
            printHelp(rawArgs);
            return EXIT_CODE_OK;
        }
        verbose = F.exist(rawArgs, CMD_VERBOSE::equalsIgnoreCase);
        ConnectionAndSslParameters args = new CommonArgParser(logger).parseAndValidate(rawArgs.iterator());
        Command command = args.command();
        commandName = command.name();
        GridClientConfiguration clientCfg = getClientConfiguration(args);
        int tryConnectMaxCount = 3;
        boolean suppliedAuth = !F.isEmpty(args.userName()) && !F.isEmpty(args.password());
        boolean credentialsRequested = false;
        while (true) {
            try {
                if (!args.autoConfirmation()) {
                    command.prepareConfirmation(clientCfg);
                    if (!confirm(command.confirmationPrompt())) {
                        logger.info("Operation cancelled.");
                        return EXIT_CODE_OK;
                    }
                }
                logger.info("Command [" + commandName + "] started");
                logger.info("Arguments: " + argumentsToString(rawArgs));
                logger.info(DELIM);
                lastOperationRes = command.execute(clientCfg, logger, args.verbose());
                break;
            } catch (Throwable e) {
                if (!isAuthError(e))
                    throw e;
                if (suppliedAuth)
                    throw new GridClientAuthenticationException("Wrong credentials.");
                if (tryConnectMaxCount == 0) {
                    throw new GridClientAuthenticationException("Maximum number of " + "retries exceeded");
                }
                logger.info(credentialsRequested ? "Authentication error, please try again." : "This cluster requires authentication.");
                if (credentialsRequested)
                    tryConnectMaxCount--;
                String user = retrieveUserName(args, clientCfg);
                String pwd = new String(requestPasswordFromConsole("password: "));
                clientCfg = getClientConfiguration(user, pwd, args);
                credentialsRequested = true;
            }
        }
        logger.info("Command [" + commandName + "] finished with code: " + EXIT_CODE_OK);
        return EXIT_CODE_OK;
    } catch (IllegalArgumentException e) {
        logger.severe("Check arguments. " + errorMessage(e));
        logger.info("Command [" + commandName + "] finished with code: " + EXIT_CODE_INVALID_ARGUMENTS);
        if (verbose)
            err = e;
        return EXIT_CODE_INVALID_ARGUMENTS;
    } catch (Throwable e) {
        if (isAuthError(e)) {
            logger.severe("Authentication error. " + errorMessage(e));
            logger.info("Command [" + commandName + "] finished with code: " + ERR_AUTHENTICATION_FAILED);
            if (verbose)
                err = e;
            return ERR_AUTHENTICATION_FAILED;
        }
        if (isConnectionError(e)) {
            IgniteCheckedException cause = X.cause(e, IgniteCheckedException.class);
            if (isConnectionClosedSilentlyException(e))
                logger.severe("Connection to cluster failed. Please check firewall settings and " + "client and server are using the same SSL configuration.");
            else {
                if (isSSLMisconfigurationError(cause))
                    e = cause;
                logger.severe("Connection to cluster failed. " + errorMessage(e));
            }
            logger.info("Command [" + commandName + "] finished with code: " + EXIT_CODE_CONNECTION_FAILED);
            if (verbose)
                err = e;
            return EXIT_CODE_CONNECTION_FAILED;
        }
        if (X.hasCause(e, IllegalArgumentException.class)) {
            IllegalArgumentException iae = X.cause(e, IllegalArgumentException.class);
            logger.severe("Check arguments. " + errorMessage(iae));
            logger.info("Command [" + commandName + "] finished with code: " + EXIT_CODE_INVALID_ARGUMENTS);
            if (verbose)
                err = e;
            return EXIT_CODE_INVALID_ARGUMENTS;
        }
        logger.severe(errorMessage(e));
        logger.info("Command [" + commandName + "] finished with code: " + EXIT_CODE_UNEXPECTED_ERROR);
        err = e;
        return EXIT_CODE_UNEXPECTED_ERROR;
    } finally {
        LocalDateTime endTime = LocalDateTime.now();
        Duration diff = Duration.between(startTime, endTime);
        if (nonNull(err))
            logger.info("Error stack trace:" + System.lineSeparator() + X.getFullStackTrace(err));
        logger.info("Control utility has completed execution at: " + endTime.format(formatter));
        logger.info("Execution time: " + diff.toMillis() + " ms");
        Arrays.stream(logger.getHandlers()).filter(handler -> handler instanceof FileHandler).forEach(Handler::close);
    }
}
Also used : LocalDateTime(java.time.LocalDateTime) Arrays(java.util.Arrays) COPYRIGHT(org.apache.ignite.internal.IgniteVersionUtils.COPYRIGHT) INDENT(org.apache.ignite.internal.commandline.CommandLogger.INDENT) Scanner(java.util.Scanner) CMD_VERBOSE(org.apache.ignite.internal.commandline.CommonArgParser.CMD_VERBOSE) Formatter(java.util.logging.Formatter) IgniteSystemProperties(org.apache.ignite.IgniteSystemProperties) GridClientHandshakeException(org.apache.ignite.internal.client.GridClientHandshakeException) FileHandler(java.util.logging.FileHandler) SecurityCredentialsProvider(org.apache.ignite.plugin.security.SecurityCredentialsProvider) SB(org.apache.ignite.internal.util.typedef.internal.SB) SecurityCredentials(org.apache.ignite.plugin.security.SecurityCredentials) Duration(java.time.Duration) X(org.apache.ignite.internal.util.typedef.X) SslContextFactory(org.apache.ignite.ssl.SslContextFactory) DFLT_HOST(org.apache.ignite.internal.commandline.TaskExecutor.DFLT_HOST) DFLT_PORT(org.apache.ignite.internal.commandline.TaskExecutor.DFLT_PORT) CommandLogger.optional(org.apache.ignite.internal.commandline.CommandLogger.optional) CMD_AUTO_CONFIRMATION(org.apache.ignite.internal.commandline.CommonArgParser.CMD_AUTO_CONFIRMATION) ACK_VER_STR(org.apache.ignite.internal.IgniteVersionUtils.ACK_VER_STR) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) JavaLoggerFormatter(org.apache.ignite.logger.java.JavaLoggerFormatter) GridClientConnectionResetException(org.apache.ignite.internal.client.impl.connection.GridClientConnectionResetException) UUID(java.util.UUID) LogRecord(java.util.logging.LogRecord) Logger(java.util.logging.Logger) GridSslBasicContextFactory(org.apache.ignite.internal.client.ssl.GridSslBasicContextFactory) Collectors(java.util.stream.Collectors) CommonArgParser.getCommonOptions(org.apache.ignite.internal.commandline.CommonArgParser.getCommonOptions) GridClientDisconnectedException(org.apache.ignite.internal.client.GridClientDisconnectedException) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Handler(java.util.logging.Handler) NotNull(org.jetbrains.annotations.NotNull) Objects.nonNull(java.util.Objects.nonNull) SecurityCredentialsBasicProvider(org.apache.ignite.plugin.security.SecurityCredentialsBasicProvider) System.lineSeparator(java.lang.System.lineSeparator) LocalDateTime(java.time.LocalDateTime) U(org.apache.ignite.internal.util.typedef.internal.U) DOUBLE_INDENT(org.apache.ignite.internal.commandline.CommandLogger.DOUBLE_INDENT) GridServerUnreachableException(org.apache.ignite.internal.client.GridServerUnreachableException) Level(java.util.logging.Level) DFLT_SSL_PROTOCOL(org.apache.ignite.ssl.SslContextFactory.DFLT_SSL_PROTOCOL) GridClientAuthenticationException(org.apache.ignite.internal.client.GridClientAuthenticationException) StreamHandler(java.util.logging.StreamHandler) GridClientClosedException(org.apache.ignite.internal.client.GridClientClosedException) F(org.apache.ignite.internal.util.typedef.F) JavaLoggerFileHandler(org.apache.ignite.logger.java.JavaLoggerFileHandler) GridClientConfiguration(org.apache.ignite.internal.client.GridClientConfiguration) File(java.io.File) CommandLogger.errorMessage(org.apache.ignite.internal.commandline.CommandLogger.errorMessage) DateTimeFormatter(java.time.format.DateTimeFormatter) IGNITE_ENABLE_EXPERIMENTAL_COMMAND(org.apache.ignite.IgniteSystemProperties.IGNITE_ENABLE_EXPERIMENTAL_COMMAND) CMD_ENABLE_EXPERIMENTAL(org.apache.ignite.internal.commandline.CommonArgParser.CMD_ENABLE_EXPERIMENTAL) Collections(java.util.Collections) FileHandler(java.util.logging.FileHandler) Handler(java.util.logging.Handler) StreamHandler(java.util.logging.StreamHandler) JavaLoggerFileHandler(org.apache.ignite.logger.java.JavaLoggerFileHandler) Duration(java.time.Duration) FileHandler(java.util.logging.FileHandler) JavaLoggerFileHandler(org.apache.ignite.logger.java.JavaLoggerFileHandler) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridClientAuthenticationException(org.apache.ignite.internal.client.GridClientAuthenticationException) GridClientConfiguration(org.apache.ignite.internal.client.GridClientConfiguration)

Example 44 with Formatter

use of java.util.logging.Formatter in project ignite by apache.

the class GridCommandHandlerClusterByClassTest method testErrUnexpectedWithWithoutVerbose.

/**
 * Test checks that stack trace for unexpected error will be output with or
 * without {@link CommonArgParser#CMD_VERBOSE} flag.
 */
@Test
public void testErrUnexpectedWithWithoutVerbose() {
    injectTestSystemOut();
    Logger log = CommandHandler.initLogger(null);
    log.addHandler(new StreamHandler(System.out, new Formatter() {

        /**
         * {@inheritDoc}
         */
        @Override
        public String format(LogRecord record) {
            String msg = record.getMessage();
            if (msg.contains("Cluster state:"))
                throw new Error();
            return msg + "\n";
        }
    }));
    int resCode = EXIT_CODE_UNEXPECTED_ERROR;
    CommandHandler cmd = new CommandHandler(log);
    assertEquals(resCode, execute(cmd, BASELINE.text()));
    assertContains(GridAbstractTest.log, testOut.toString(), ERROR_STACK_TRACE_PREFIX);
    assertEquals(resCode, execute(cmd, BASELINE.text(), CMD_VERBOSE));
    assertContains(GridAbstractTest.log, testOut.toString(), ERROR_STACK_TRACE_PREFIX);
}
Also used : LogRecord(java.util.logging.LogRecord) Formatter(java.util.logging.Formatter) StreamHandler(java.util.logging.StreamHandler) CommandHandler(org.apache.ignite.internal.commandline.CommandHandler) Logger(java.util.logging.Logger) GridAbstractTest(org.apache.ignite.testframework.junits.GridAbstractTest) Test(org.junit.Test)

Aggregations

Formatter (java.util.logging.Formatter)44 LogRecord (java.util.logging.LogRecord)18 File (java.io.File)13 SimpleFormatter (java.util.logging.SimpleFormatter)12 IOException (java.io.IOException)11 Logger (java.util.logging.Logger)11 FileHandler (java.util.logging.FileHandler)10 Handler (java.util.logging.Handler)9 Date (java.util.Date)6 Test (org.junit.Test)6 SimpleDateFormat (java.text.SimpleDateFormat)5 ConsoleHandler (java.util.logging.ConsoleHandler)5 Config (edu.neu.ccs.pyramid.configuration.Config)4 JSONLogFormatter (fish.payara.enterprise.server.logging.JSONLogFormatter)4 Level (java.util.logging.Level)4 StreamHandler (java.util.logging.StreamHandler)4 Pair (edu.neu.ccs.pyramid.util.Pair)3 DateFormat (java.text.DateFormat)3 ErrorManager (java.util.logging.ErrorManager)3 Filter (java.util.logging.Filter)3