Example usage for java.util.logging Logger addHandler

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

Introduction

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

Prototype

public void addHandler(Handler handler) throws SecurityException 

Source Link

Document

Add a log Handler to receive logging messages.

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);//www  .  j a v a2s. c  om
    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: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);//from www.  jav  a 2s . co  m
    logger.addHandler(fh);
    addToManifest(filename, MANIFEST_LOG_FILE, shouldManifest);
    logger.setUseParentHandlers(false);
    this.fileHandlers.put(logger, fh);
}

From source file:org.ejbca.ui.tcp.CmpTcpServer.java

public void start() throws UnknownHostException {
    final String cmdHandle = org.ejbca.ui.tcp.CmpTcpCommandHandler.class.getName();

    myServer = new QuickServer();
    myServer.setClientAuthenticationHandler(null);
    myServer.setBindAddr(CmpTcpConfiguration.getTCPBindAdress());
    myServer.setPort(CmpTcpConfiguration.getTCPPortNumber());
    myServer.setName("CMP TCP Server v " + VER);
    if (QuickServer.getVersionNo() >= 1.2) {
        LOG.info("Using 1.2 feature");
        myServer.setClientBinaryHandler(cmdHandle);
        myServer.setClientEventHandler(cmdHandle);

        //reduce info to Console
        myServer.setConsoleLoggingToMicro();
    }/*from  w w w. j  av  a  2s. co m*/

    //setup logger to log to file
    Logger logger = null;
    FileHandler txtLog = null;
    final String logDir = CmpTcpConfiguration.getTCPLogDir();
    final File logFile = new File(logDir + "/");
    if (!logFile.canRead()) {
        logFile.mkdir();
    }
    try {
        logger = Logger.getLogger("");
        logger.setLevel(Level.INFO);

        logger = Logger.getLogger("cmptcpserver");
        logger.setLevel(Level.FINEST);
        txtLog = new FileHandler(logDir + "/cmptcpserver.log");
        //reduce info 
        txtLog.setFormatter(new org.quickserver.util.logging.MicroFormatter());
        logger.addHandler(txtLog);

        myServer.setAppLogger(logger); //imp

        //myServer.setConsoleLoggingToMicro();
        myServer.setConsoleLoggingFormatter("org.quickserver.util.logging.SimpleTextFormatter");
        myServer.setConsoleLoggingLevel(Level.INFO);
    } catch (Exception e) {
        LOG.error("Could not create xmlLog FileHandler : ", e);
    }
    try {
        final String confFile = CmpTcpConfiguration.getTCPConfigFile();
        if (!StringUtils.isEmpty(confFile)) {
            final Object config[] = new Object[] { confFile };
            if (!myServer.initService(config)) {
                LOG.error("Configuration from config file " + confFile + " failed!");
            }
        }
        myServer.startServer();
        //myServer.getQSAdminServer().setShellEnable(true);
        //myServer.startQSAdminServer();         
    } catch (AppException e) {
        LOG.error("Error in server : ", e);
    }
}

From source file:org.jenkinsci.remoting.protocol.ProtocolStackTest.java

@Test
public void initSequence() throws IOException {
    Logger logger = Logger.getLogger(ProtocolStack.class.getName());
    CapturingHandler handler = new CapturingHandler();
    assertThat(logger.isLoggable(Level.FINEST), is(false));
    Level oldLevel = logger.getLevel();
    logger.addHandler(handler);
    try {// w  ww. j a  v  a2  s .co m
        logger.setLevel(Level.FINEST);
        assertThat(logger.isLoggable(Level.FINEST), is(true));
        final AtomicInteger state = new AtomicInteger();
        ProtocolStack.on(new NetworkLayer(selector) {

            @Override
            protected void write(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void start() throws IOException {
                state.compareAndSet(0, 1);
            }

            @Override
            public void doCloseSend() throws IOException {

            }

            @Override
            public void doCloseRecv() {

            }

            @Override
            public boolean isSendOpen() {
                return true;
            }

        }).filter(new FilterLayer() {
            @Override
            public void start() throws IOException {
                state.compareAndSet(1, 2);
            }

            @Override
            public void onRecv(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void doSend(@NonNull ByteBuffer data) throws IOException {

            }

        }).filter(new FilterLayer() {
            @Override
            public void start() throws IOException {
                state.compareAndSet(2, 3);
            }

            @Override
            public void onRecv(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void doSend(@NonNull ByteBuffer data) throws IOException {

            }

        }).named("initSeq").build(new ApplicationLayer<Void>() {
            @Override
            public Void get() {
                return null;
            }

            @Override
            public void onRead(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void start() throws IOException {
                state.compareAndSet(3, 4);
            }

            @Override
            public void onReadClosed(IOException cause) throws IOException {

            }

            @Override
            public boolean isReadOpen() {
                return true;
            }

        });
        assertThat("Init in sequence", state.get(), is(4));
        assertThat(handler.logRecords,
                contains(
                        allOf(hasProperty("message", is("[{0}] Initializing")),
                                hasProperty("parameters", is(new Object[] { "initSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Starting")),
                                hasProperty("parameters", is(new Object[] { "initSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Started")),
                                hasProperty("parameters", is(new Object[] { "initSeq" })))));
    } finally {
        logger.removeHandler(handler);
        logger.setLevel(oldLevel);
    }
}

From source file:org.jenkinsci.remoting.protocol.ProtocolStackTest.java

@Test
public void initSequenceFailure() throws IOException {
    Logger logger = Logger.getLogger(ProtocolStack.class.getName());
    CapturingHandler handler = new CapturingHandler();
    assertThat(logger.isLoggable(Level.FINEST), is(false));
    Level oldLevel = logger.getLevel();
    logger.addHandler(handler);
    try {/*from  www  . j  ava2  s.c  o  m*/
        logger.setLevel(Level.FINEST);
        assertThat(logger.isLoggable(Level.FINEST), is(true));
        final AtomicInteger state = new AtomicInteger();
        try {
            ProtocolStack.on(new NetworkLayer(selector) {

                @Override
                protected void write(@NonNull ByteBuffer data) throws IOException {

                }

                @Override
                public void start() throws IOException {
                    state.compareAndSet(0, 1);
                }

                @Override
                public void doCloseSend() throws IOException {

                }

                @Override
                public void doCloseRecv() {

                }

                @Override
                public boolean isSendOpen() {
                    return true;
                }

            }).filter(new FilterLayer() {
                @Override
                public void start() throws IOException {
                    state.compareAndSet(1, 2);
                    throw new IOException("boom");
                }

                @Override
                public void onRecv(@NonNull ByteBuffer data) throws IOException {

                }

                @Override
                public void doSend(@NonNull ByteBuffer data) throws IOException {

                }

            }).filter(new FilterLayer() {
                @Override
                public void start() throws IOException {
                    state.set(-2);
                }

                @Override
                public void onRecv(@NonNull ByteBuffer data) throws IOException {

                }

                @Override
                public void doSend(@NonNull ByteBuffer data) throws IOException {

                }

                @Override
                public void onRecvClosed(IOException cause) throws IOException {
                    state.compareAndSet(2, 3);
                    super.onRecvClosed(cause);
                }
            }).named("initSeq").build(new ApplicationLayer<Void>() {
                @Override
                public Void get() {
                    return null;
                }

                @Override
                public void onRead(@NonNull ByteBuffer data) throws IOException {

                }

                @Override
                public void start() throws IOException {
                    state.set(-3);
                }

                @Override
                public void onReadClosed(IOException cause) throws IOException {
                    state.compareAndSet(3, 4);
                }

                @Override
                public boolean isReadOpen() {
                    return true;
                }

            });
            fail("Expecting IOException");
        } catch (IOException e) {
            assertThat(e.getMessage(), is("boom"));
        }
        assertThat(handler.logRecords,
                contains(
                        allOf(hasProperty("message", is("[{0}] Initializing")),
                                hasProperty("parameters", is(new Object[] { "initSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Starting")),
                                hasProperty("parameters", is(new Object[] { "initSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Start failure")),
                                hasProperty("parameters", is(new Object[] { "initSeq" })),
                                hasProperty("thrown", hasProperty("message", is("boom"))))));
        assertThat("Init in sequence", state.get(), is(4));
    } finally {
        logger.removeHandler(handler);
        logger.setLevel(oldLevel);
    }
}

From source file:org.apache.oodt.cas.pge.PGETaskInstance.java

protected Logger createLogger() throws IOException, PGEException {
    File logDir = new File(pgeConfig.getExeDir(), "logs");
    if (!(logDir.exists() || logDir.mkdirs())) {
        throw new PGEException("mkdirs for logs directory return false");
    }/*from  w  ww.ja va 2s  .c  o  m*/

    Logger logger = Logger.getLogger(PGETaskInstance.class.getName() + "." + workflowInstId);
    FileHandler handler = new FileHandler(new File(logDir, createLogFileName()).getAbsolutePath());
    handler.setEncoding("UTF-8");
    handler.setFormatter(new SimpleFormatter());
    logger.addHandler(handler);
    return logger;
}

From source file:org.jenkinsci.remoting.protocol.ProtocolStackTest.java

@Test
public void stackCloseSequence() throws IOException {
    Logger logger = Logger.getLogger(ProtocolStack.class.getName());
    CapturingHandler handler = new CapturingHandler();
    assertThat(logger.isLoggable(Level.FINEST), is(false));
    Level oldLevel = logger.getLevel();
    logger.addHandler(handler);
    try {/*  w  w  w  .j a  v a  2s.com*/
        logger.setLevel(Level.FINEST);
        assertThat(logger.isLoggable(Level.FINEST), is(true));

        final AtomicInteger state = new AtomicInteger();
        ProtocolStack.on(new NetworkLayer(selector) {

            @Override
            public void start() throws IOException {
            }

            @Override
            protected void write(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void doCloseRecv() {
                state.compareAndSet(3, 4);
                onRecvClosed();

            }

            @Override
            public void doCloseSend() throws IOException {
                state.compareAndSet(2, 3);
                doCloseRecv();
            }

            @Override
            public boolean isSendOpen() {
                return true;
            }

        }).filter(new FilterLayer() {
            @Override
            public void start() throws IOException {
            }

            @Override
            public void onRecv(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void doSend(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void doCloseSend() throws IOException {
                state.compareAndSet(1, 2);
                super.doCloseSend();
            }

            @Override
            public void onRecvClosed(IOException cause) throws IOException {
                state.compareAndSet(4, 5);
                super.onRecvClosed(cause);
            }
        }).filter(new FilterLayer() {
            @Override
            public void start() throws IOException {
            }

            @Override
            public void onRecv(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void doSend(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public void doCloseSend() throws IOException {
                state.compareAndSet(0, 1);
                super.doCloseSend();
            }

            @Override
            public void onRecvClosed(IOException cause) throws IOException {
                state.compareAndSet(5, 6);
                super.onRecvClosed(cause);
            }
        }).named("closeSeq").build(new ApplicationLayer<Void>() {
            @Override
            public boolean isReadOpen() {
                return true;
            }

            @Override
            public void onRead(@NonNull ByteBuffer data) throws IOException {

            }

            @Override
            public Void get() {
                return null;
            }

            @Override
            public void start() throws IOException {
            }

            @Override
            public void onReadClosed(IOException cause) throws IOException {
                state.compareAndSet(6, 7);
            }

        }).close();
        assertThat("Close in sequence", state.get(), is(7));
        assertThat(handler.logRecords,
                contains(
                        allOf(hasProperty("message", is("[{0}] Initializing")),
                                hasProperty("parameters", is(new Object[] { "closeSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Starting")),
                                hasProperty("parameters", is(new Object[] { "closeSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Started")),
                                hasProperty("parameters", is(new Object[] { "closeSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Closing")),
                                hasProperty("parameters", is(new Object[] { "closeSeq" }))),
                        allOf(hasProperty("message", is("[{0}] Closed")),
                                hasProperty("parameters", is(new Object[] { "closeSeq" })))));
    } finally {
        logger.removeHandler(handler);
        logger.setLevel(oldLevel);
    }
}

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

private void setupAlertLog(String logsPath) throws IOException {
    Logger logger = Logger.getLogger(LOGNAME_ALERTS + "." + logsPath);
    String filename = getAlertsLogPath().getFile().getAbsolutePath();
    GenerationFileHandler fh = GenerationFileHandler.makeNew(filename, false, true);
    fh.setFormatter(new SimpleFormatter());
    AlertThreadGroup.current().addLogger(logger);
    AlertHandler.ensureStaticInitialization();
    logger.addHandler(fh);
    addToManifest(filename, MANIFEST_LOG_FILE, true);
    logger.setUseParentHandlers(false);/* w w  w .  j a  v a  2  s  . c  om*/
    this.fileHandlers.put(logger, fh);
}

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/*w w w  .  j a  v  a 2 s. c om*/
        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();
        }
    });
}