Example usage for java.util.logging Logger setLevel

List of usage examples for java.util.logging Logger setLevel

Introduction

In this page you can find the example usage for java.util.logging Logger setLevel.

Prototype

public void setLevel(Level newLevel) throws SecurityException 

Source Link

Document

Set the log level specifying which message levels will be logged by this logger.

Usage

From source file:org.cloudifysource.esc.shell.commands.BootstrapCloud.java

private void restoreLoggingLevel() {
    if (!verbose) {
        final Set<Entry<String, Level>> entries = loggerStates.entrySet();
        for (final Entry<String, Level> entry : entries) {
            final Logger provisioningLogger = Logger.getLogger(entry.getKey());
            provisioningLogger.setLevel(entry.getValue());
        }/*from  w ww  .jav  a2  s  .com*/
    }

}

From source file:com.cisco.oss.foundation.logging.FoundationLogger.java

private static void setupJULSupport(URL resource) {
    boolean julSupportEnabled = Boolean.valueOf(log4jConfigProps
            .getProperty(FoundationLoggerConstants.Foundation_JUL_SUPPORT_ENABLED.toString(), "false"));
    if (julSupportEnabled) {
        String appenderRef = log4jConfigProps
                .getProperty(FoundationLoggerConstants.Foundation_JUL_APPENDER_REF.toString());

        if (StringUtils.isBlank(appenderRef)) {

            Enumeration allAppenders = Logger.getRootLogger().getAllAppenders();

            while (allAppenders.hasMoreElements()) {

                Appender appender = (Appender) allAppenders.nextElement();

                if (appender instanceof FileAppender) {
                    appenderRef = appender.getName();
                    getLogger(FoundationLogger.class)
                            .info("*** Using '" + appenderRef + "' as the Java util logging appender ref ***");
                    System.err.println(
                            "*** Using '" + appenderRef + "' as the Java util logging appender ref ***");
                    break;
                }//from ww  w  .j av a 2  s .com
            }
        }

        if (StringUtils.isBlank(appenderRef)) {
            throw new IllegalArgumentException(
                    "Java util support was enabled but couldn't find a matching appender under the '"
                            + FoundationLoggerConstants.Foundation_JUL_APPENDER_REF.toString() + "' key.");
        }

        Handler handler = null;

        Appender appender = Logger.getRootLogger().getAppender(appenderRef);
        if (appender == null) {

            Enumeration allAppenders = Logger.getRootLogger().getAllAppenders();

            while (allAppenders.hasMoreElements()) {

                Appender tempAppender = (Appender) allAppenders.nextElement();

                if (tempAppender instanceof AsyncAppender) {

                    AsyncAppender asyncAppender = (AsyncAppender) tempAppender;
                    Enumeration asyncAppenderAllAppenders = asyncAppender.getAllAppenders();

                    while (asyncAppenderAllAppenders.hasMoreElements()) {

                        Appender asyncTempAppender = (Appender) asyncAppenderAllAppenders.nextElement();

                        if (appenderRef.equals(asyncTempAppender.getName())) {
                            appender = asyncTempAppender;
                            break;
                        }
                    }
                    if (appender != null) {
                        break;
                    }
                }
            }
        }

        if (appender instanceof FileAppender) {
            try {
                handler = new FileHandler(((FileAppender) appender).getFile());
            } catch (IOException e) {
                throw new IllegalArgumentException(
                        "IOException encountered when trying to setup jul logging: " + e, e);
            }
        } else if (appender instanceof ConsoleAppender) {
            handler = new ConsoleHandler();
        } else {
            getLogger(FoundationLogger.class)
                    .error("got a reference to an unsupported appender: " + appenderRef);
        }

        if (handler != null) {

            //                System.setProperty("java.util.logging.config.file",resource.getPath());

            java.util.logging.LogManager.getLogManager().reset();
            try {
                java.util.logging.LogManager.getLogManager().readConfiguration(resource.openStream());
            } catch (IOException e) {
                throw new IllegalArgumentException(
                        "IOException encountered when trying to read log4j properties file: " + e, e);
            }

            handler.setLevel(java.util.logging.Level.FINEST);
            handler.setFormatter(new FoundationLogFormatter());

            java.util.logging.Logger rootLogger = java.util.logging.Logger.getLogger("");
            rootLogger.addHandler(handler);
            rootLogger.setLevel(java.util.logging.Level.SEVERE);

            Properties julLoggerSubset = getPropertiesSubset("jul.logger");
            if (!julLoggerSubset.isEmpty()) {
                Set<Object> keySet = julLoggerSubset.keySet();
                for (Object key : keySet) {
                    java.util.logging.Logger logger = java.util.logging.Logger.getLogger((String) key);
                    logger.setLevel(java.util.logging.Level.parse((String) julLoggerSubset.get(key)));
                }
            }
        }

    }
}

From source file:com.github.stephenc.mongodb.maven.StartMongoMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {//  w  w w .java  2 s  .  c o  m
        getLog().info("Skipping mongodb: mongodb.skip==true");
        return;
    }
    if (installation == null) {
        getLog().info("Using mongod from PATH");
    } else {
        getLog().info("Using mongod installed in " + installation);
    }
    getLog().info("Using database root of " + databaseRoot);
    final Logger mongoLogger = Logger.getLogger("com.mongodb");
    Level mongoLevel = mongoLogger.getLevel();
    try {
        mongoLogger.setLevel(Level.SEVERE);
        MongoOptions opts = new MongoOptions();
        opts.autoConnectRetry = false;
        opts.connectionsPerHost = 1;
        opts.connectTimeout = 50;
        opts.socketTimeout = 50;
        Mongo instance;
        try {
            instance = new Mongo(new ServerAddress("localhost", port), opts);
            List<String> databaseNames = instance.getDatabaseNames();
            throw new MojoExecutionException("Port " + port
                    + " is already running a MongoDb instance with the following databases " + databaseNames);
        } catch (MongoException.Network e) {
            // fine... no instance running
        } catch (MongoException e) {
            throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance");
        } catch (UnknownHostException e) {
            // ignore... localhost is always known!
        }
    } finally {
        mongoLogger.setLevel(mongoLevel);
    }

    CommandLine commandLine = null;
    if (installation != null && installation.isDirectory()) {
        File bin = new File(installation, "bin");
        File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod");
        if (exe.isFile()) {
            commandLine = new CommandLine(exe);
        } else {
            throw new MojoExecutionException("Could not find mongo executables in specified installation: "
                    + installation + " expected to find " + exe + " but it does not exist.");
        }
    }
    if (commandLine == null) {
        commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod");
    }
    if (databaseRoot.isFile()) {
        throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory");
    }
    if (databaseRoot.isDirectory() && cleanDatabaseRoot) {
        getLog().info("Cleaning database root directory: " + databaseRoot);
        try {
            FileUtils.deleteDirectory(databaseRoot);
        } catch (IOException e) {
            throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e);
        }
    }
    if (!databaseRoot.isDirectory()) {
        getLog().debug("Creating database root directory: " + databaseRoot);
        if (!databaseRoot.mkdirs()) {
            throw new MojoExecutionException("Could not create database root directory " + databaseRoot);
        }
    }

    if (!verbose) {
        commandLine.addArgument("--quiet");
    }

    commandLine.addArgument("--logpath");
    commandLine.addArgument(logPath.getAbsolutePath());
    if (logAppend) {
        commandLine.addArgument("--logappend");
    }

    commandLine.addArgument(auth ? "--auth" : "--noauth");

    commandLine.addArgument("--port");
    commandLine.addArgument(Integer.toString(port));

    commandLine.addArgument("--dbpath");
    commandLine.addArgument(databaseRoot.getAbsolutePath());

    if (additionalArguments != null) {
        for (String aa : additionalArguments) {
            commandLine.addArgument(aa);
        }
    }

    Executor exec = new DefaultExecutor();
    DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler();
    exec.setWorkingDirectory(databaseRoot);
    ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer());
    exec.setProcessDestroyer(processObserver);

    LogOutputStream stdout = new MavenLogOutputStream(getLog());
    LogOutputStream stderr = new MavenLogOutputStream(getLog());

    getLog().info("Executing command line: " + commandLine);
    exec.setStreamHandler(new PumpStreamHandler(stdout, stderr));
    try {
        exec.execute(commandLine, execHandler);
        getLog().info("Waiting for MongoDB to start...");
        long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120);
        mongoLevel = mongoLogger.getLevel();
        try {
            mongoLogger.setLevel(Level.SEVERE);
            while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) {
                MongoOptions opts = new MongoOptions();
                opts.autoConnectRetry = false;
                opts.connectionsPerHost = 1;
                opts.connectTimeout = 250;
                opts.socketTimeout = 250;
                Mongo instance;
                try {
                    instance = new Mongo(new ServerAddress("localhost", port), opts);
                    List<String> databaseNames = instance.getDatabaseNames();
                    getLog().info("MongoDb started.");
                    getLog().info("Databases: " + databaseNames);
                } catch (MongoException.Network e) {
                    // ignore, wait and try again
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e1) {
                        // ignore
                    }
                    continue;
                } catch (MongoException e) {
                    getLog().info("MongoDb started.");
                    getLog().info("Unable to list databases due to " + e.getMessage());
                }
                break;
            }
        } finally {
            mongoLogger.setLevel(mongoLevel);
        }
        if (execHandler.hasResult()) {
            ExecuteException exception = execHandler.getException();
            if (exception != null) {
                throw new MojoFailureException(exception.getMessage(), exception);
            }
            throw new MojoFailureException(
                    "Command " + commandLine + " exited with exit code " + execHandler.getExitValue());
        }
        Map pluginContext = session.getPluginContext(getPluginDescriptor(), project);
        pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}

From source file:org.cloudifysource.esc.shell.commands.BootstrapCloud.java

private void limitLoggingLevel() {

    if (!this.verbose) {
        loggerStates.clear();//from   w  w w  . j  a  va2s  .c o  m
        for (final String loggerName : NON_VERBOSE_LOGGERS) {
            final Logger provisioningLogger = Logger.getLogger(loggerName);
            final Level logLevelBefore = provisioningLogger.getLevel();
            provisioningLogger.setLevel(Level.WARNING);
            loggerStates.put(loggerName, logLevelBefore);
        }
    }
}

From source file:org.archive.crawler.reporting.CrawlerLoggerModule.java

private void setupLogFile(Logger logger, String filename, Formatter f, boolean shouldManifest)
        throws IOException, SecurityException {
    logger.setLevel(Level.INFO); // set all standard loggers to INFO
    GenerationFileHandler fh = GenerationFileHandler.makeNew(filename, false, shouldManifest);
    fh.setFormatter(f);//www  .j  a v a  2  s. c  om
    logger.addHandler(fh);
    addToManifest(filename, MANIFEST_LOG_FILE, shouldManifest);
    logger.setUseParentHandlers(false);
    this.fileHandlers.put(logger, fh);
}

From source file:org.callimachusproject.repository.CalliRepository.java

private void setLoggerLevel(String fragment, Level level) {
    boolean found = false;
    Enumeration<String> names = LogManager.getLogManager().getLoggerNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        if (name.contains(fragment)) {
            Logger logger = Logger.getLogger(name);
            logger.setLevel(level);
            setHandlerLevel(logger, level);
            found = true;/*from www . ja  v  a 2  s  .  c om*/
        }
    }
    if (!found)
        throw new IllegalArgumentException("No such logger: " + fragment);
}

From source file:org.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java

/**
 * Inits the search logger./*  ww  w  .  j a  v  a 2 s. co  m*/
 */
private void initSearchLogger(Connection connection) {
    Logger logger = Logger.getAnonymousLogger();
    loggers.put(connection.getId(), logger);
    logger.setLevel(Level.ALL);

    String logfileName = ConnectionManager.getSearchLogFileName(connection);
    try {
        FileHandler fileHandler = new FileHandler(logfileName, getFileSizeInKb() * 1000, getFileCount(), true);
        fileHandlers.put(connection.getId(), fileHandler);
        fileHandler.setFormatter(new Formatter() {
            public String format(LogRecord record) {
                return record.getMessage();
            }
        });
        logger.addHandler(fileHandler);
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.rivalry.example.illyriad.IllyriadDataCollector.java

/**
 * @return a new web driver.//  w  w  w . j  a  v a  2s  . co  m
 */
private WebDriver createWebDriver() {
    final WebDriver answer = new HtmlUnitDriver();

    final Logger logger = Logger.getLogger("");
    logger.setLevel(Level.OFF);

    if (answer instanceof HtmlUnitDriver) {
        ((HtmlUnitDriver) answer).setJavascriptEnabled(true);
    }

    return answer;
}

From source file:edu.usu.sdl.openstorefront.web.rest.service.Application.java

@PUT
@RequireAdmin//from  w ww.  j  a  v  a 2  s. c om
@APIDescription("Sets logger level")
@Produces({ MediaType.APPLICATION_JSON })
@Consumes({ MediaType.WILDCARD })
@DataType(LoggerView.class)
@Path("/logger/{loggername}/level")
public Response updateApplicationProperty(@PathParam("loggername") @RequiredParam String loggername,
        String level) {
    Response response = Response.status(Response.Status.NOT_FOUND).build();
    Logger logger = LogManager.getLogManager().getLogger(loggername);
    if (logger != null) {
        List<String> levels = loadLevels();
        boolean saved = false;
        if (StringUtils.isBlank(level)) {
            logger.setLevel(null);
            saved = true;
        } else {
            if (levels.contains(level)) {
                logger.setLevel(Level.parse(level));
                saved = true;
            } else {
                RestErrorModel restErrorModel = new RestErrorModel();
                restErrorModel.getErrors().put("level", "Log level is not valid. Check level value passed in.");
                response = Response.ok(restErrorModel).build();
            }
        }
        if (saved) {
            LoggerView loggerView = new LoggerView();
            loggerView.setName(loggername);
            loggerView.setLevel(level);
            for (Handler handlerLocal : logger.getHandlers()) {
                loggerView.getHandlers()
                        .add(handlerLocal.getClass().getName() + " = " + handlerLocal.getLevel().getName());
            }
            response = Response.ok(loggerView).build();
        }
    }
    return response;
}

From source file:com.yahoo.dba.perf.myperf.common.MyPerfContext.java

private void configureLogging() {
    Logger logger = Logger.getLogger("");
    try {/*  ww w  . j a  v  a2  s  . c  o  m*/
        logger.setLevel(Level.parse(getLogLevel()));
    } catch (Exception ex) {
        logger.setLevel(Level.INFO);
    }
    try {
        for (Handler h : logger.getHandlers()) {
            if (h instanceof java.util.logging.ConsoleHandler)
                h.setLevel(Level.SEVERE);
        }
        String logRoot = System.getProperty("logPath", ".");

        java.util.logging.FileHandler fileHandler = new java.util.logging.FileHandler(
                logRoot + File.separatorChar + getLogPath(), this.logFileSize, this.logFileCount);
        fileHandler.setLevel(logger.getLevel());
        fileHandler.setFormatter(new SimpleFormatter());
        logger.addHandler(fileHandler);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}