Example usage for java.util.logging Handler setLevel

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

Introduction

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

Prototype

public synchronized void setLevel(Level newLevel) throws SecurityException 

Source Link

Document

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

Usage

From source file:com.speed.ob.Obfuscator.java

public Obfuscator(final Config config) {
    transforms = new LinkedList<>();
    store = new ClassStore();
    this.config = config;
    //set up logging
    this.LOGGER = Logger.getLogger(this.getClass().getName());
    LOGGER.info("Ob2 is starting");
    String logLvl = config.get("Obfuscator.logging");
    String logDir = config.get("Obfuscator.log_dir");
    level = parseLevel(logLvl);// w w  w  .  j  a v a2  s  . com
    LOGGER.info("Logger level set to " + level.getName());
    Logger topLevel = Logger.getLogger("");
    topLevel.setLevel(level);
    File logs = new File(logDir);
    if (!logs.exists()) {
        if (!logs.mkdir())
            Logger.getLogger(this.getClass().getName()).warning("Could not create logging directory");
    }
    try {
        if (logs.exists()) {
            fHandler = new FileHandler(logs.getAbsolutePath() + File.separator + "ob%g.log");
            topLevel.addHandler(fHandler);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    for (Handler handler : topLevel.getHandlers()) {
        handler.setLevel(level);
    }
    //populate transforms
    LOGGER.info("Configuring Ob");
    LOGGER.fine("Parsing config");
    if (config.getBoolean("Obfuscator.all_transforms")) {
        LOGGER.fine("Adding all transforms");
        transforms.add(ClassNameTransform.class);
    } else {
        if (config.getBoolean("Obfuscator.classname_obfuscation")) {
            LOGGER.fine("Adding class name transform");
            transforms.add(ClassNameTransform.class);
        }
        if (config.getBoolean("Obfuscator.controlflow_obfuscation")) {
            LOGGER.fine("Control flow obfuscation not added, transform does not exist");
        }
        if (config.getBoolean("Obfuscator.string_obfuscation")) {
            LOGGER.fine("String obfuscation not added, transform does not exist");

        }
        if (config.getBoolean("Obfuscator.fieldname_transforms")) {
            LOGGER.fine("Field name obfuscation not added, transform does not exist");

        }
        if (config.getBoolean("Obfuscator.methodname_transforms")) {
            LOGGER.fine("Method name obfuscation not added, transform does not exist");

        }
    }
    LOGGER.info("Loaded " + transforms.size() + " transforms");
    String inputFile = config.get("Obfuscator.input");
    LOGGER.fine("Checking input file(s) and output directory");
    String outFile = config.get("Obfuscator.out_dir");
    out = new File(outFile);
    if (inputFile == null || inputFile.isEmpty()) {
        LOGGER.severe("Input file not specified in config");
        throw new RuntimeException("Input file not specified");
    } else {
        in = new File(inputFile);
        if (!in.exists()) {
            LOGGER.severe("Input file not found");
            throw new RuntimeException("Input file not found");
        }
        LOGGER.fine("Attempting to initialise classes");
        if (in.isDirectory()) {
            try {
                store.init(in.listFiles(), false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (in.getName().endsWith(".class")) {
            try {
                store.init(new File[] { in }, false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (in.getName().endsWith(".jar")) {
            try {
                JarInputStream in = new JarInputStream(new FileInputStream(this.in));
                store.init(in, out, this.in);
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        LOGGER.info("Loaded " + store.nodes().size() + " classes");
    }
    if (!out.exists()) {
        LOGGER.fine("Attempting to make output directory");
        if (!out.mkdir()) {
            LOGGER.severe("Could not make output directory");
            throw new RuntimeException("Could not create output dir: " + out.getAbsolutePath());
        }
    } else if (!out.isDirectory()) {
        LOGGER.severe("Output directory is a file");
        throw new RuntimeException(out.getName() + " is not a directory, cannot output there");
    } else {
        if (!out.canWrite()) {
            LOGGER.severe("Cannot write to output directory");
            throw new RuntimeException("Cannot write to output dir: " + out.getAbsolutePath());
        }
    }

}

From source file:de.crowdcode.kissmda.maven.plugin.KissMdaMojo.java

private void setLoggingLevel() {
    Logger log = LogManager.getLogManager().getLogger("");

    if (loggingLevel == null || loggingLevel.equals("")) {
        log.setLevel(Level.INFO);
    } else {//from  w ww.j a v  a2s .c om
        log.setLevel(loggingLevelMapper.getLevel(loggingLevel));
    }

    for (Handler handler : log.getHandlers()) {
        if (loggingLevel == null || loggingLevel.equals("")) {
            handler.setLevel(Level.INFO);
        } else {
            handler.setLevel(loggingLevelMapper.getLevel(loggingLevel));
        }
    }
}

From source file:gtu.youtube.JavaYoutubeDownloader.java

private void explicitlySetAllLogging(Level myLevel, Level globalLevel) {
    rootlog.setLevel(Level.ALL);//from ww  w  . j a v  a  2 s  .  c  om
    for (Handler handler : rootlog.getHandlers()) {
        handler.setLevel(Level.ALL);
    }
    log.setLevel(myLevel);
    rootlog.setLevel(globalLevel);
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

private void initLogging() {
    java.util.logging.Logger logger = java.util.logging.Logger.getLogger("javax.security.sasl");
    logger.setLevel(java.util.logging.Level.FINEST);
    logger.addHandler(new java.util.logging.ConsoleHandler());
    for (java.util.logging.Handler handler : logger.getHandlers()) {
        handler.setLevel(java.util.logging.Level.FINEST);
    }//from w w w  .j  av a  2s.co m
}

From source file:com.redhat.rcm.version.Cli.java

private static void configureLogging(boolean useConsole, final boolean useLogFile, final File logFile) {
    System.out.println("Log file is: " + logFile.getAbsolutePath());

    final List<Handler> handlers = new ArrayList<Handler>();

    if (!useConsole && !useLogFile) {
        if (!useLogFile) {
            System.out.println(/*www .jav a  2s .  co  m*/
                    "\n\nNOTE: --no-console option has been OVERRIDDEN since --no-log-file option was also provided.\nOutputting to console ONLY.\n");
            useConsole = true;
        }
    }

    if (useConsole) {
        final Handler chandler = new ConsoleHandler();
        chandler.setFormatter(new VManFormatter());
        chandler.setLevel(Level.ALL);
        handlers.add(chandler);
    }

    if (useLogFile) {
        try {
            final File dir = logFile.getParentFile();
            if (dir != null && !dir.isDirectory() && !dir.mkdirs()) {
                throw new RuntimeException(
                        "Failed to create parent directory for logfile: " + dir.getAbsolutePath());
            }
            final Handler fhandler = new FileHandler(logFile.getPath(), false);
            fhandler.setFormatter(new VManFormatter());
            fhandler.setLevel(Level.ALL);
            handlers.add(fhandler);
        } catch (final IOException e) {
            final StringWriter sw = new StringWriter();
            final PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            System.out.printf("ERROR: Failed to initialize log file: %s. Reason: %s\n\n%s\n\n", logFile,
                    e.getMessage(), sw.toString());

            throw new RuntimeException("Failed to initialize logfile.");
        }
    }

    root.setUseParentHandlers(false);
    final Handler[] currenthandlers = root.getHandlers();
    for (final Handler h : currenthandlers) {
        h.close();
        root.removeHandler(h);
    }
    for (final Handler h : handlers) {
        root.addHandler(h);
    }
}

From source file:com.googlecode.fightinglayoutbugs.FightingLayoutBugs.java

private void enableDebugOutputToConsole(Logger logger) {
    do {/*  w w w  . java2 s.com*/
        for (final Handler handler : logger.getHandlers()) {
            if (handler instanceof ConsoleHandler) {
                final Level originalConsoleLogLevel = handler.getLevel();
                handler.setLevel(Level.FINE);
                _runAfterAnalysis.add(new Runnable() {
                    @Override
                    public void run() {
                        handler.setLevel(originalConsoleLogLevel);
                    }
                });
            }
        }
    } while (logger.getUseParentHandlers() && (logger = logger.getParent()) != null);
}

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

private void setHandlerLevel(Logger logger, Level level) {
    if (logger.getParent() != null) {
        setHandlerLevel(logger.getParent(), level);
    }// ww w. j  a  v  a  2 s. c  o  m
    Handler[] handlers = logger.getHandlers();
    if (handlers != null) {
        for (Handler handler : handlers) {
            if (handler.getLevel().intValue() > level.intValue()) {
                handler.setLevel(level);
            }
        }
    }
}

From source file:org.jenkinsci.plugins.workflow.support.steps.ExecutorStepTest.java

@Test
public void buildShellScriptAcrossDisconnect() throws Exception {
    Assume.assumeFalse("TODO not sure how to write a corresponding batch script", Functions.isWindows());
    story.addStep(new Statement() {
        @SuppressWarnings("SleepWhileInLoop")
        @Override//  ww w. j  av a  2s  .  co  m
        public void evaluate() throws Throwable {
            Logger LOGGER = Logger.getLogger(DurableTaskStep.class.getName());
            LOGGER.setLevel(Level.FINE);
            Handler handler = new ConsoleHandler();
            handler.setLevel(Level.ALL);
            LOGGER.addHandler(handler);
            DumbSlave s = new DumbSlave("dumbo", "dummy", tmp.getRoot().getAbsolutePath(), "1",
                    Node.Mode.NORMAL, "", new JNLPLauncher(), RetentionStrategy.NOOP,
                    Collections.<NodeProperty<?>>emptyList());
            story.j.jenkins.addNode(s);
            startJnlpProc();
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "demo");
            File f1 = new File(story.j.jenkins.getRootDir(), "f1");
            File f2 = new File(story.j.jenkins.getRootDir(), "f2");
            new FileOutputStream(f1).close();
            p.setDefinition(new CpsFlowDefinition("node('dumbo') {\n" + "    sh 'touch \"" + f2
                    + "\"; while [ -f \"" + f1 + "\" ]; do sleep 1; done; echo finished waiting; rm \"" + f2
                    + "\"'\n" + "    echo 'OK, done'\n" + "}", true));
            WorkflowRun b = p.scheduleBuild2(0).waitForStart();
            while (!f2.isFile()) {
                Thread.sleep(100);
            }
            assertTrue(b.isBuilding());
            Computer c = s.toComputer();
            assertNotNull(c);
            killJnlpProc();
            while (c.isOnline()) {
                Thread.sleep(100);
            }
            startJnlpProc();
            while (c.isOffline()) {
                Thread.sleep(100);
            }
            assertTrue(f2.isFile());
            assertTrue(f1.delete());
            while (f2.isFile()) {
                Thread.sleep(100);
            }
            story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b));
            story.j.assertLogContains("finished waiting", b); // TODO sometimes is not printed to log, despite f2 having been removed
            story.j.assertLogContains("OK, done", b);
            killJnlpProc();
        }
    });
}

From source file:org.jenkinsci.plugins.workflow.support.steps.ExecutorStepTest.java

@Test
public void buildShellScriptAcrossRestart() throws Exception {
    Assume.assumeFalse("TODO not sure how to write a corresponding batch script", Functions.isWindows());
    story.addStep(new Statement() {
        @SuppressWarnings("SleepWhileInLoop")
        @Override//from  ww  w. j av a 2s .  c o m
        public void evaluate() throws Throwable {
            Logger LOGGER = Logger.getLogger(DurableTaskStep.class.getName());
            LOGGER.setLevel(Level.FINE);
            Handler handler = new ConsoleHandler();
            handler.setLevel(Level.ALL);
            LOGGER.addHandler(handler);
            // Cannot use regular JenkinsRule.createSlave due to JENKINS-26398.
            // Nor can we can use JenkinsRule.createComputerLauncher, since spawned commands are killed by CommandLauncher somehow (it is not clear how; apparently before its onClosed kills them off).
            DumbSlave s = new DumbSlave("dumbo", "dummy", tmp.getRoot().getAbsolutePath(), "1",
                    Node.Mode.NORMAL, "", new JNLPLauncher(), RetentionStrategy.NOOP,
                    Collections.<NodeProperty<?>>emptyList());
            story.j.jenkins.addNode(s);
            startJnlpProc();
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "demo");
            File f1 = new File(story.j.jenkins.getRootDir(), "f1");
            File f2 = new File(story.j.jenkins.getRootDir(), "f2");
            new FileOutputStream(f1).close();
            p.setDefinition(new CpsFlowDefinition("node('dumbo') {\n" + "    sh 'touch \"" + f2
                    + "\"; while [ -f \"" + f1 + "\" ]; do sleep 1; done; echo finished waiting; rm \"" + f2
                    + "\"'\n" + "    echo 'OK, done'\n" + "}", true));
            WorkflowRun b = p.scheduleBuild2(0).waitForStart();
            while (!f2.isFile()) {
                Thread.sleep(100);
            }
            assertTrue(b.isBuilding());
            killJnlpProc();
        }
    });
    story.addStep(new Statement() {
        @Override
        public void evaluate() throws Throwable {
            WorkflowJob p = (WorkflowJob) story.j.jenkins.getItem("demo");
            WorkflowRun b = p.getLastBuild();
            assertTrue(b.isBuilding()); // TODO occasionally fails; log ends with: Running: Allocate node : Body : Start (no shell step in sight)
            startJnlpProc(); // Have to relaunch JNLP agent, since the Jenkins port has changed, and we cannot force JenkinsRule to reuse the same port as before.
            File f1 = new File(story.j.jenkins.getRootDir(), "f1");
            File f2 = new File(story.j.jenkins.getRootDir(), "f2");
            assertTrue(f2.isFile());
            assertTrue(f1.delete());
            while (f2.isFile()) {
                Thread.sleep(100);
            }
            story.j.assertBuildStatusSuccess(story.j.waitForCompletion(b));
            story.j.assertLogContains("finished waiting", b);
            story.j.assertLogContains("OK, done", b);
            killJnlpProc();
        }
    });
}

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

private void configureLogging() {
    Logger logger = Logger.getLogger("");
    try {/* w w w  . j a  va 2 s  .  co 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();
    }
}