Example usage for java.util.logging Logger setUseParentHandlers

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

Introduction

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

Prototype

public void setUseParentHandlers(boolean useParentHandlers) 

Source Link

Document

Specify whether or not this logger should send its output to its parent Logger.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Logger logger = Logger.getLogger("com.mycompany");

    // Stop forwarding log records to ancestor handlers
    logger.setUseParentHandlers(false);

    // Start forwarding log records to ancestor handlers
    logger.setUseParentHandlers(true);/*from   w w w  . j  a va  2s  . co  m*/
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    Logger logger = Logger.getLogger("your.logging");
    ConsoleHandler handler = new ConsoleHandler();
    MemoryHandler mHandler = new MemoryHandler(handler, 10, Level.ALL);
    logger.addHandler(mHandler);/* w  ww  . ja  va  2  s .  co m*/
    logger.setUseParentHandlers(false);
    LogRecord record1 = new LogRecord(Level.SEVERE, "This is SEVERE level message");
    LogRecord record2 = new LogRecord(Level.WARNING, "This is WARNING level message");
    logger.log(record1);
    logger.log(record2);
}

From source file:net.nharyes.drivecopy.Main.java

public static void main(String[] args) {

    // set logger handler
    Logger logger = Logger.getLogger(Main.class.getPackage().getName());
    logger.setUseParentHandlers(false);
    logger.addHandler(new SystemOutHandler());
    logger.setLevel(Level.FINE);//ww w  . j a v  a  2  s  .co m

    new Main(args);
}

From source file:de.burlov.amazon.s3.dirsync.CLI.java

/**
 * @param args/*from   w w w.  ja v a2  s  . c om*/
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Logger.getLogger("").setLevel(Level.OFF);
    Logger deLogger = Logger.getLogger("de");
    deLogger.setLevel(Level.INFO);
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new VerySimpleFormatter());
    deLogger.addHandler(handler);
    deLogger.setUseParentHandlers(false);
    //      if (true)
    //      {
    //         LogFactory.getLog(CLI.class).error("test msg", new Exception("test extception"));
    //         return;
    //      }
    Options opts = new Options();
    OptionGroup gr = new OptionGroup();

    /*
     * Befehlsgruppe initialisieren
     */
    gr = new OptionGroup();
    gr.setRequired(true);
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download changed or new files").create(CMD_UPDATE));
    gr.addOption(OptionBuilder.withArgName("up|down").hasArg()
            .withDescription("Upload/Download directory snapshot").create(CMD_SNAPSHOT));
    gr.addOption(OptionBuilder.withDescription("Delete remote folder").create(CMD_DELETE_DIR));
    gr.addOption(OptionBuilder.withDescription("Delete a bucket").create(CMD_DELETE_BUCKET));
    gr.addOption(OptionBuilder.create(CMD_HELP));
    gr.addOption(OptionBuilder.create(CMD_VERSION));
    gr.addOption(OptionBuilder.withDescription("Prints summary for stored data").create(CMD_SUMMARY));
    gr.addOption(OptionBuilder.withDescription("Clean up orphaned objekts").create(CMD_CLEANUP));
    gr.addOption(OptionBuilder.withDescription("Changes encryption password").withArgName("new password")
            .hasArg().create(CMD_CHANGE_PASSWORD));
    gr.addOption(OptionBuilder.withDescription("Lists all buckets").create(CMD_LIST_BUCKETS));
    gr.addOption(OptionBuilder.withDescription("Lists raw objects in a bucket").create(CMD_LIST_BUCKET));
    gr.addOption(OptionBuilder.withDescription("Lists files in remote folder").create(CMD_LIST_DIR));
    opts.addOptionGroup(gr);
    /*
     * Parametergruppe initialisieren
     */
    opts.addOption(OptionBuilder.withArgName("key").isRequired(false).hasArg().withDescription("S3 access key")
            .create(OPT_S3S_KEY));
    opts.addOption(OptionBuilder.withArgName("secret").isRequired(false).hasArg()
            .withDescription("Secret key for S3 account").create(OPT_S3S_SECRET));
    opts.addOption(OptionBuilder.withArgName("bucket").isRequired(false).hasArg().withDescription(
            "Optional bucket name for storage. If not specified then an unique bucket name will be generated")
            .create(OPT_BUCKET));
    // opts.addOption(OptionBuilder.withArgName("US|EU").hasArg().
    // withDescription(
    // "Where the new bucket should be created. Default US").create(
    // OPT_LOCATION));
    opts.addOption(OptionBuilder.withArgName("path").isRequired(false).hasArg()
            .withDescription("Local directory path").create(OPT_LOCAL_DIR));
    opts.addOption(OptionBuilder.withArgName("name").isRequired(false).hasArg()
            .withDescription("Remote directory name").create(OPT_REMOTE_DIR));
    opts.addOption(OptionBuilder.withArgName("password").isRequired(false).hasArg()
            .withDescription("Encryption password").create(OPT_ENC_PASSWORD));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs()
            .withDescription("Comma separated exclude file patterns like '*.tmp,*/dir/*.tmp'")
            .create(OPT_EXCLUDE_PATTERNS));
    opts.addOption(OptionBuilder.withArgName("patterns").hasArgs().withDescription(
            "Comma separated include patterns like '*.java'. If not specified, then all files in specified local directory will be included")
            .create(OPT_INCLUDE_PATTERNS));

    if (args.length == 0) {
        printUsage(opts);
        return;
    }

    CommandLine cmd = null;
    try {
        cmd = new GnuParser().parse(opts, args);
        if (cmd.hasOption(CMD_HELP)) {
            printUsage(opts);
            return;
        }
        if (cmd.hasOption(CMD_VERSION)) {
            System.out.println("s3dirsync version " + Version.CURRENT_VERSION);
            return;
        }
        String awsKey = cmd.getOptionValue(OPT_S3S_KEY);
        String awsSecret = cmd.getOptionValue(OPT_S3S_SECRET);
        String bucket = cmd.getOptionValue(OPT_BUCKET);
        String bucketLocation = cmd.getOptionValue(OPT_LOCATION);
        String localDir = cmd.getOptionValue(OPT_LOCAL_DIR);
        String remoteDir = cmd.getOptionValue(OPT_REMOTE_DIR);
        String password = cmd.getOptionValue(OPT_ENC_PASSWORD);
        String exclude = cmd.getOptionValue(OPT_EXCLUDE_PATTERNS);
        String include = cmd.getOptionValue(OPT_INCLUDE_PATTERNS);

        if (StringUtils.isBlank(awsKey) || StringUtils.isBlank(awsSecret)) {
            System.out.println("S3 account data required");
            return;
        }

        if (StringUtils.isBlank(bucket)) {
            bucket = awsKey + ".dirsync";
        }

        if (cmd.hasOption(CMD_DELETE_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            int deleted = S3Utils.deleteBucket(awsKey, awsSecret, bucket);
            System.out.println("Deleted objects: " + deleted);
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKETS)) {
            for (String str : S3Utils.listBuckets(awsKey, awsSecret)) {
                System.out.println(str);
            }
            return;
        }
        if (cmd.hasOption(CMD_LIST_BUCKET)) {
            if (StringUtils.isBlank(bucket)) {
                System.out.println("Bucket name required");
                return;
            }
            for (String str : S3Utils.listObjects(awsKey, awsSecret, bucket)) {
                System.out.println(str);
            }
            return;
        }
        if (StringUtils.isBlank(password)) {
            System.out.println("Encryption password required");
            return;
        }
        char[] psw = password.toCharArray();
        DirSync ds = new DirSync(awsKey, awsSecret, bucket, bucketLocation, psw);
        ds.setExcludePatterns(parseSubargumenths(exclude));
        ds.setIncludePatterns(parseSubargumenths(include));
        if (cmd.hasOption(CMD_SUMMARY)) {
            ds.printStorageSummary();
            return;
        }
        if (StringUtils.isBlank(remoteDir)) {
            System.out.println("Remote directory name required");
            return;
        }
        if (cmd.hasOption(CMD_DELETE_DIR)) {
            ds.deleteFolder(remoteDir);
            return;
        }
        if (cmd.hasOption(CMD_LIST_DIR)) {
            Folder folder = ds.getFolder(remoteDir);
            if (folder == null) {
                System.out.println("No such folder found: " + remoteDir);
                return;
            }
            for (Map.Entry<String, FileInfo> entry : folder.getIndexData().entrySet()) {
                System.out.println(entry.getKey() + " ("
                        + FileUtils.byteCountToDisplaySize(entry.getValue().getLength()) + ")");
            }
            return;
        }
        if (cmd.hasOption(CMD_CLEANUP)) {
            ds.cleanUp();
            return;
        }
        if (cmd.hasOption(CMD_CHANGE_PASSWORD)) {
            String newPassword = cmd.getOptionValue(CMD_CHANGE_PASSWORD);
            if (StringUtils.isBlank(newPassword)) {
                System.out.println("new password required");
                return;
            }
            char[] chars = newPassword.toCharArray();
            ds.changePassword(chars);
            newPassword = null;
            Arrays.fill(chars, ' ');
            return;
        }
        if (StringUtils.isBlank(localDir)) {
            System.out.println(OPT_LOCAL_DIR + " argument required");
            return;
        }
        String direction = "";
        boolean up = false;
        boolean snapshot = false;
        if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_UPDATE))) {
            direction = cmd.getOptionValue(CMD_UPDATE);
        } else if (StringUtils.isNotBlank(cmd.getOptionValue(CMD_SNAPSHOT))) {
            direction = cmd.getOptionValue(CMD_SNAPSHOT);
            snapshot = true;
        }
        if (StringUtils.isBlank(direction)) {
            System.out.println("Operation direction required");
            return;
        }
        up = StringUtils.equalsIgnoreCase(OPT_UP, direction);
        File baseDir = new File(localDir);
        if (!baseDir.exists() && !baseDir.mkdirs()) {
            System.out.println("Invalid local directory: " + baseDir.getAbsolutePath());
            return;
        }
        ds.syncFolder(baseDir, remoteDir, up, snapshot);

    } catch (DirSyncException e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printUsage(opts);

    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:edu.uiuc.ncsa.myproxy.MyProxyLogon.java

/**
 * Provides a simple command-line interface.
 *//* www  . ja v  a  2s  .  c om*/
public static void main(String[] args) {
    try {
        Logger logger = Logger.getLogger(MyProxyLogon.class.getName());
        logger.setUseParentHandlers(false);
        MyLoggingFacade facade = new MyLoggingFacade(logger);
        MyProxyLogon m = new MyProxyLogon(facade);

        //MyLoggingFacade myLoggingFacade = new MyLoggingFacade(MyProxyLogon.class.getName());
        //MyProxyLogon m = new MyProxyLogon(myLoggingFacade);
        // Console cons = System.console();
        String passphrase = null;
        X509Certificate[] CAcerts;
        X509CRL[] CRLs;
        //MyProxyLogon.logger.setLevel(Level.ALL);
        // Turn on for debugging if needed.
        // if (cons != null) {
        // char[] pass = cons.readPassword("[%s]", "MyProxy Passphrase:
        // ");
        // if (pass != null) {
        // passphrase = new String(pass);
        // }
        // } else {
        System.out.println("Warning: terminal will echo passphrase as you type.");
        System.out.print("MyProxy Passphrase: ");
        passphrase = m.readLine(System.in);
        // }
        if (passphrase == null) {
            System.err.println("Error reading passphrase.");
            System.exit(1);
        }
        m.setPassphrase(passphrase);
        m.requestTrustRoots(true);
        m.getCredentials();
        m.writeProxyFile();
        System.out.println("Credential written successfully.");
        CAcerts = m.getTrustedCAs();
        if (CAcerts != null) {
            System.out.println(Integer.toString(CAcerts.length) + " CA certificates received.");
        }
        CRLs = m.getCRLs();
        if (CRLs != null) {
            System.out.println(Integer.toString(CRLs.length) + " CRLs received.");
        }
        if (m.writeTrustRoots()) {
            System.out.println("Wrote trust roots to " + MyProxyLogon.getTrustRootPath() + ".");
        } else {
            System.out.println("Received no trust roots from MyProxy server.");
        }
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:NewApplication.java

/**
 * @param args the command line arguments
 *//*ww  w.  j  a  v a 2s  .c om*/
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewApplication.class.getName()).log(java.util.logging.Level.SEVERE,
                null, ex);
    }
    //</editor-fold>

    Logger log = Logger.getLogger("NewApplication");
    try {
        FileInputStream fis = new FileInputStream("p.properties");
        LogManager.getLogManager().readConfiguration(fis);
        log.setLevel(Level.FINE);
        log.addHandler(new java.util.logging.ConsoleHandler());
        log.setUseParentHandlers(false);

        log.info("starting NewApplication");
        fis.close();
    } catch (Exception e) {
    }
    ;

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewApplication().setVisible(true);
        }
    });
}

From source file:com.mobius.software.mqtt.performance.controller.ControllerRunner.java

private static void configureConsoleLogger() {
    Logger l = Logger.getLogger("org.glassfish.grizzly.http.server.HttpHandler");
    l.setLevel(Level.INFO);//from   w w w  . ja va 2 s  . c  o  m
    l.setUseParentHandlers(false);
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(Level.INFO);
    l.addHandler(ch);
}

From source file:prm4j.indexing.monitor.ParametricMonitorLogger.java

/**
 * A simple file logger which outputs only the message.
 * /* w ww  .  j av a 2 s. c  om*/
 * @param fileName
 *            path to the output file
 * @return the logger
 */
private static Logger getFileLogger(String fileName) {
    // make sure parent directories exist
    new File(fileName).getParentFile().mkdirs();
    final Logger logger = Logger.getLogger(fileName);
    try {
        logger.setUseParentHandlers(false);
        Handler handler = new FileHandler(fileName, true);
        handler.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                return record.getMessage() + "\n";
            }
        });
        logger.addHandler(handler);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return logger;
}

From source file:com.elasticbox.jenkins.k8s.cfg.TestDiscoverLocalKubernetesCloud.java

@Initializer(after = InitMilestone.EXTENSIONS_AUGMENTED)
public static void initTestBeforePluginInitializer() throws Exception {
    testLogHandler.clear();/*from w  w  w . j  a v  a 2 s.  co  m*/

    Logger logger = Logger.getLogger("com.elasticbox.jenkins.k8s");
    logger.setUseParentHandlers(false);
    logger.addHandler(testLogHandler);

    Mockito.when(kubernetesRepositoryMock.testConnection(Mockito.anyString())).thenReturn(true);
    PluginInitializer.kubeRepository = kubernetesRepositoryMock;
    PluginInitializer.KUBE_TOKEN_PATH = PluginInitializer.class.getResource("fakeToken").getFile();
}

From source file:com.google.oacurl.util.LoggingConfig.java

public static void enableWireLog() {
    // For clarity, override the formatter so that it doesn't print the
    // date and method name for each line, and then munge the output a little
    // bit to make it nicer and more curl-like.
    Formatter wireFormatter = new Formatter() {
        @Override/*w  w  w. ja  v a2s .  c  o  m*/
        public String format(LogRecord record) {
            String message = record.getMessage();
            String trimmedMessage = message.substring(">> \"".length(), message.length() - 1);
            if (trimmedMessage.matches("[0-9a-f]+\\[EOL\\]")) {
                return "";
            }

            trimmedMessage = trimmedMessage.replace("[EOL]", "");
            if (trimmedMessage.isEmpty()) {
                return "";
            }

            StringBuilder out = new StringBuilder();
            out.append(message.charAt(0));
            out.append(" ");
            out.append(trimmedMessage);
            out.append(System.getProperty("line.separator"));
            return out.toString();
        }
    };

    ConsoleHandler wireHandler = new ConsoleHandler();
    wireHandler.setLevel(Level.FINE);
    wireHandler.setFormatter(wireFormatter);

    Logger wireLogger = Logger.getLogger("org.apache.http.wire");
    wireLogger.setLevel(Level.FINE);
    wireLogger.setUseParentHandlers(false);
    wireLogger.addHandler(wireHandler);
}