Example usage for java.util.logging ConsoleHandler ConsoleHandler

List of usage examples for java.util.logging ConsoleHandler ConsoleHandler

Introduction

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

Prototype

public ConsoleHandler() 

Source Link

Document

Create a ConsoleHandler for System.err .

Usage

From source file:Main.java

/**
 * Tells Java's Logging infrastructure to output whatever it possibly can, this is only needed
 * in Java, not in Android./*from  w ww .j a  v a 2 s  . c  o  m*/
 */
public static void outputAsMuchLoggingAsPossible() {
    Logger log = Logger.getLogger("com.couchbase.lite");
    ConsoleHandler handler = new ConsoleHandler();
    handler.setLevel(Level.ALL);
    log.addHandler(handler);
    log.setLevel(Level.ALL);
}

From source file:jshm.logging.Log.java

public static void configTestLogging() {
    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(Level.ALL);
    consoleHandler.setFormatter(new OneLineFormatter());

    Logger cur = Logger.getLogger("");
    removeHandlers(cur);/*  w  ww  .j  a  v a  2 s .  c o  m*/
    //      cur.setLevel(Level.ALL);

    cur.addHandler(consoleHandler);

    cur = Logger.getLogger("jshm");
    cur.setLevel(Level.ALL);

    cur = Logger.getLogger("httpclient.wire.header");
    cur.setLevel(Level.ALL);

    //      cur = Logger.getLogger("org.hibernate");
    //      removeHandlers(cur);
    //      
    //      cur.setLevel(Level.INFO);
}

From source file:jshm.logging.Log.java

public static void reloadConfig() throws Exception {
    // all logging
    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(DEBUG ? Level.ALL : Level.WARNING);
    consoleHandler.setFormatter(new OneLineFormatter());

    Logger cur = Logger.getLogger("");
    removeHandlers(cur);/*from   w ww .java  2  s. c  om*/

    cur.addHandler(consoleHandler);

    // jshm logging
    Formatter fileFormatter = new FileFormatter();
    Handler jshmHandler = new FileHandler("data/logs/JSHManager.txt");
    jshmHandler.setLevel(Level.ALL);
    jshmHandler.setFormatter(fileFormatter);

    cur = Logger.getLogger("jshm");
    cur.addHandler(jshmHandler);
    cur.setLevel(DEBUG ? Level.ALL : Level.INFO);

    // hibernate logging
    Handler hibernateHandler = new FileHandler("data/logs/Hibernate.txt");
    hibernateHandler.setLevel(Level.ALL);
    hibernateHandler.setFormatter(fileFormatter);

    cur = Logger.getLogger("org.hibernate");
    removeHandlers(cur);

    cur.addHandler(hibernateHandler);
    cur.setLevel(DEBUG ? Level.INFO : Level.WARNING);

    // HttpClient logging
    Handler httpClientHandler = new FileHandler("data/logs/HttpClient.txt");
    httpClientHandler.setLevel(Level.ALL);
    httpClientHandler.setFormatter(fileFormatter);

    //      cur = Logger.getLogger("httpclient.wire");
    cur = Logger.getLogger("httpclient.wire.header");
    removeHandlers(cur);

    cur.addHandler(httpClientHandler);
    cur.setLevel(DEBUG ? Level.ALL : Level.INFO);

    cur = Logger.getLogger("org.apache.commons.httpclient");
    removeHandlers(cur);

    cur.addHandler(httpClientHandler);
    cur.setLevel(DEBUG ? Level.FINER : Level.INFO);

    // HtmlParser logging
    Handler htmlParserHandler = new FileHandler("data/logs/HtmlParser.txt");
    htmlParserHandler.setLevel(Level.ALL);
    htmlParserHandler.setFormatter(fileFormatter);

    cur = Logger.getLogger("org.htmlparser");
    removeHandlers(cur);

    cur.addHandler(htmlParserHandler);
    cur.setLevel(DEBUG ? Level.ALL : Level.INFO);

    // SwingX logging
    Handler swingxHandler = new FileHandler("data/logs/SwingX.txt");
    swingxHandler.setLevel(Level.ALL);
    swingxHandler.setFormatter(fileFormatter);

    cur = Logger.getLogger("org.jdesktop.swingx");
    removeHandlers(cur);

    cur.addHandler(swingxHandler);
    cur.setLevel(DEBUG ? Level.ALL : Level.INFO);
}

From source file:org.archive.crawler.processor.recrawl.PersistProcessor.java

/**
 * Utility main for importing a log into a BDB-JE environment or moving a
 * database between environments (2 arguments), or simply dumping a log
 * to stderr in a more readable format (1 argument). 
 * // w ww.  j a v a2s  .  c om
 * @param args command-line arguments
 * @throws DatabaseException
 * @throws IOException
 */
public static void main(String[] args) throws DatabaseException, IOException {
    Handler handler = new ConsoleHandler();
    handler.setLevel(Level.ALL);
    handler.setFormatter(new OneLineSimpleLogger());
    logger.addHandler(handler);
    logger.setUseParentHandlers(false);

    if (args.length == 2) {
        logger.setLevel(Level.INFO);
        populatePersistEnv(args[0], new File(args[1]));
    } else if (args.length == 1) {
        logger.setLevel(Level.FINE);
        populatePersistEnv(args[0], null);
    } else {
        System.out.println("Arguments: ");
        System.out.println("    source [target]");
        System.out.println("...where source is either a txtser log file or BDB env dir");
        System.out.println("and target, if present, is a BDB env dir. ");
        return;
    }
}

From source file:jenkins.model.RunIdMigratorTest.java

@BeforeClass
public static void logging() {
    RunIdMigrator.LOGGER.setLevel(Level.ALL);
    Handler handler = new ConsoleHandler();
    handler.setLevel(Level.ALL);/*from   ww  w  . j  a v  a  2 s  .c o  m*/
    RunIdMigrator.LOGGER.addHandler(handler);
}

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//from  w  w w.j a v a  2s  . com
        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);
}

From source file:asl.seedscan.DQAWeb.java

public static void findConsoleHandler() {
    // Locate the global logger's ConsoleHandler if it exists
    Logger globalLogger = Logger.getLogger("");
    for (Handler handler : globalLogger.getHandlers()) {
        if (handler instanceof ConsoleHandler) {
            consoleHandler = handler;// w w  w  .  ja va  2  s .co  m
            break;
        }
    }

    // Ensure the global logger has an attached ConsoleHandler
    // creating one for it if necessary
    if (consoleHandler == null) {
        consoleHandler = new ConsoleHandler();
        globalLogger.addHandler(consoleHandler);
    }
}

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);//  w w  w .  j  ava2 s  .c  om
    l.setUseParentHandlers(false);
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(Level.INFO);
    l.addHandler(ch);
}

From source file:net.tradelib.apps.StrategyBacktest.java

public static void run(Strategy strategy) throws Exception {
    // Setup the logging
    System.setProperty("java.util.logging.SimpleFormatter.format",
            "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n");
    LogManager.getLogManager().reset();
    Logger rootLogger = Logger.getLogger("");
    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("file.log", "true"))) {
        FileHandler logHandler = new FileHandler("diag.out", 8 * 1024 * 1024, 2, true);
        logHandler.setFormatter(new SimpleFormatter());
        logHandler.setLevel(Level.FINEST);
        rootLogger.addHandler(logHandler);
    }//w  w w.  ja v  a  2s .c  o  m

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("console.log", "true"))) {
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(new SimpleFormatter());
        consoleHandler.setLevel(Level.INFO);
        rootLogger.addHandler(consoleHandler);
    }

    rootLogger.setLevel(Level.INFO);

    // Setup Hibernate
    // Configuration configuration = new Configuration();
    // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    // SessionFactory factory = configuration.buildSessionFactory(builder.build());

    Context context = new Context();
    context.dbUrl = BacktestCfg.instance().getProperty("db.url");

    HistoricalDataFeed hdf = new SQLDataFeed(context);
    hdf.configure(BacktestCfg.instance().getProperty("datafeed.config", "config/datafeed.properties"));
    context.historicalDataFeed = hdf;

    HistoricalReplay hr = new HistoricalReplay(context);
    context.broker = hr;

    strategy.initialize(context);
    strategy.cleanupDb();

    long start = System.nanoTime();
    strategy.start();
    long elapsedTime = System.nanoTime() - start;
    System.out.println("backtest took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    start = System.nanoTime();
    strategy.updateEndEquity();
    strategy.writeExecutionsAndTrades();
    strategy.writeEquity();
    elapsedTime = System.nanoTime() - start;
    System.out
            .println("writing to the database took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    System.out.println();

    // Write the strategy totals to the database
    strategy.totalTradeStats();

    // Write the strategy report to the database and obtain the JSON
    // for writing it to the console.
    JsonObject report = strategy.writeStrategyReport();

    JsonArray asa = report.getAsJsonArray("annual_stats");

    String csvPath = BacktestCfg.instance().getProperty("positions.csv.prefix");
    if (!Strings.isNullOrEmpty(csvPath)) {
        csvPath += "-" + strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE)
                + ".csv";
    }

    String ordersCsvPath = BacktestCfg.instance().getProperty("orders.csv.suffix");
    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        ordersCsvPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + ordersCsvPath;
    }

    String actionsPath = BacktestCfg.instance().getProperty("actions.file.suffix");
    if (!Strings.isNullOrEmpty(actionsPath)) {
        actionsPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + actionsPath;
    }

    // If emails are being send out
    String signalText = StrategyText.build(context.dbUrl, strategy.getName(),
            strategy.getLastTimestamp().toLocalDate(), "   ", csvPath, '|');

    System.out.println(signalText);
    System.out.println();

    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        StrategyText.buildOrdersCsv(context.dbUrl, strategy.getName(),
                strategy.getLastTimestamp().toLocalDate(), ordersCsvPath);
    }

    File actionsFile = Strings.isNullOrEmpty(actionsPath) ? null : new File(actionsPath);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile,
                signalText + System.getProperty("line.separator") + System.getProperty("line.separator"));
    }

    String message = "";

    if (asa.size() > 0) {
        // Sort the array
        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
        for (int ii = 0; ii < asa.size(); ++ii) {
            int year = asa.get(ii).getAsJsonObject().get("year").getAsInt();
            map.put(year, ii);
        }

        for (int id : map.values()) {
            JsonObject jo = asa.get(id).getAsJsonObject();
            String yearStr = String.valueOf(jo.get("year").getAsInt());
            String pnlStr = String.format("$%,d", jo.get("pnl").getAsInt());
            String pnlPctStr = String.format("%.2f%%", jo.get("pnl_pct").getAsDouble());
            String endEqStr = String.format("$%,d", jo.get("end_equity").getAsInt());
            String ddStr = String.format("$%,d", jo.get("maxdd").getAsInt());
            String ddPctStr = String.format("%.2f%%", jo.get("maxdd_pct").getAsDouble());
            String str = yearStr + " PnL: " + pnlStr + ", PnL Pct: " + pnlPctStr + ", End Equity: " + endEqStr
                    + ", MaxDD: " + ddStr + ", Pct MaxDD: " + ddPctStr;
            message += str + "\n";
        }

        String pnlStr = String.format("$%,d", report.get("pnl").getAsInt());
        String pnlPctStr = String.format("%.2f%%", report.get("pnl_pct").getAsDouble());
        String ddStr = String.format("$%,d", report.get("avgdd").getAsInt());
        String ddPctStr = String.format("%.2f%%", report.get("avgdd_pct").getAsDouble());
        String gainToPainStr = String.format("%.4f", report.get("gain_to_pain").getAsDouble());
        String str = "\nAvg PnL: " + pnlStr + ", Pct Avg PnL: " + pnlPctStr + ", Avg DD: " + ddStr
                + ", Pct Avg DD: " + ddPctStr + ", Gain to Pain: " + gainToPainStr;
        message += str + "\n";
    } else {
        message += "\n";
    }

    // Global statistics
    JsonObject jo = report.getAsJsonObject("total_peak");
    String dateStr = jo.get("date").getAsString();
    int maxEndEq = jo.get("equity").getAsInt();
    jo = report.getAsJsonObject("total_maxdd");
    double cash = jo.get("cash").getAsDouble();
    double pct = jo.get("pct").getAsDouble();
    message += "\n" + "Total equity peak [" + dateStr + "]: " + String.format("$%,d", maxEndEq) + "\n"
            + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";

    if (report.has("latest_peak") && report.has("latest_maxdd")) {
        jo = report.getAsJsonObject("latest_peak");
        LocalDate ld = LocalDate.parse(jo.get("date").getAsString(), DateTimeFormatter.ISO_DATE);
        maxEndEq = jo.get("equity").getAsInt();
        jo = report.getAsJsonObject("latest_maxdd");
        cash = jo.get("cash").getAsDouble();
        pct = jo.get("pct").getAsDouble();
        message += "\n" + Integer.toString(ld.getYear()) + " equity peak ["
                + ld.format(DateTimeFormatter.ISO_DATE) + "]: " + String.format("$%,d", maxEndEq) + "\n"
                + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";
    }

    message += "\n" + "Avg Trade PnL: "
            + String.format("$%,d", Math.round(report.get("avg_trade_pnl").getAsDouble())) + ", Max DD: "
            + String.format("$%,d", Math.round(report.get("maxdd").getAsDouble())) + ", Max DD Pct: "
            + String.format("%.2f%%", report.get("maxdd_pct").getAsDouble()) + ", Num Trades: "
            + Integer.toString(report.get("num_trades").getAsInt());

    System.out.println(message);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile, message + System.getProperty("line.separator"), true);
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("email.enabled", "false"))) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.sendgrid.net");
        props.put("mail.smtp.port", "587");

        String user = BacktestCfg.instance().getProperty("email.user");
        String pass = BacktestCfg.instance().getProperty("email.pass");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pass);
            }
        });

        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(BacktestCfg.instance().getProperty("email.from")));
            msg.addRecipients(RecipientType.TO, BacktestCfg.instance().getProperty("email.recipients"));
            msg.setSubject(strategy.getName() + " Report ["
                    + strategy.getLastTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE) + "]");
            msg.setText("Positions & Signals\n" + signalText + "\n\nStatistics\n" + message);
            Transport.send(msg);
        } catch (Exception ee) {
            Logger.getLogger("").warning(ee.getMessage());
        }
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("sftp.enabled", "false"))) {
        HashMap<String, String> fileMap = new HashMap<String, String>();
        if (!Strings.isNullOrEmpty(actionsPath))
            fileMap.put(actionsPath, actionsPath);
        if (!Strings.isNullOrEmpty(ordersCsvPath))
            fileMap.put(ordersCsvPath, ordersCsvPath);
        String user = BacktestCfg.instance().getProperty("sftp.user");
        String pass = BacktestCfg.instance().getProperty("sftp.pass");
        String host = BacktestCfg.instance().getProperty("sftp.host");
        SftpUploader sftp = new SftpUploader(host, user, pass);
        sftp.upload(fileMap);
    }
}

From source file:org.forgerock.patch.Main.java

public static void execute(URL patchUrl, String originalUrlString, File workingDir, File installDir,
        Map<String, Object> params) throws IOException {

    try {/*from   ww w  .j  a  va2s  .  co m*/
        // Load the base patch configuration
        InputStream in = config.getClass().getResourceAsStream(CONFIG_PROPERTIES_FILE);
        if (in == null) {
            throw new PatchException(
                    "Unable to locate: " + CONFIG_PROPERTIES_FILE + " in: " + patchUrl.toString());
        } else {
            config.load(in);
        }

        // Configure logging and disable parent handlers
        SingleLineFormatter formatter = new SingleLineFormatter();
        Handler historyHandler = new FileHandler(workingDir + File.separator + PATCH_HISTORY_FILE, true);
        Handler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(formatter);
        historyHandler.setFormatter(formatter);
        history.setUseParentHandlers(false);
        history.addHandler(consoleHandler);
        history.addHandler(historyHandler);

        // Initialize the Archive
        Archive archive = Archive.getInstance();
        archive.initialize(installDir, new File(workingDir, PATCH_ARCHIVE_DIR),
                config.getString(PATCH_BACKUP_ARCHIVE));

        // Create the patch logger once we've got the archive directory
        Handler logHandler = new FileHandler(archive.getArchiveDirectory() + File.separator + PATCH_LOG_FILE,
                false);
        logHandler.setFormatter(formatter);
        logger.setUseParentHandlers(false);
        logger.addHandler(logHandler);

        // Instantiate the patcgh implementation and invoke the patch
        Patch patch = instantiatePatch();
        patch.initialize(patchUrl, originalUrlString, workingDir, installDir, params);
        history.log(Level.INFO, "Applying {0}, version={1}",
                new Object[] { config.getProperty(PATCH_DESCRIPTION), config.getProperty(PATCH_RELEASE) });
        history.log(Level.INFO, "Target: {0}, Source: {1}", new Object[] { installDir, patchUrl });
        patch.apply();

        history.log(Level.INFO, "Completed");
    } catch (PatchException pex) {
        history.log(Level.SEVERE, "Failed", pex);
    } catch (ConfigurationException ex) {
        history.log(Level.SEVERE, "Failed to load patch configuration", ex);
    } finally {
        try {
            Archive.getInstance().close();
        } catch (Exception ex) {
        }
        ;
    }
}