Example usage for java.util.logging LogManager getLogManager

List of usage examples for java.util.logging LogManager getLogManager

Introduction

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

Prototype

public static LogManager getLogManager() 

Source Link

Document

Returns the global LogManager object.

Usage

From source file:org.cidarlab.eugene.EugeneExecutor.java

public static Object execute(String sScript, int nReturn) throws RecognitionException {

    LogManager.getLogManager().reset();

    EugeneLexer lexer = new EugeneLexer(new ANTLRStringStream(sScript));
    CommonTokenStream tokens = new CommonTokenStream(lexer);

    EugeneParser parser = new EugeneParser(tokens);

    long t1 = System.nanoTime();
    parser.initSymbolTables();/*from  w  w w  .  j  a v a2  s .c  om*/
    long t2 = System.nanoTime();
    parser.prog();
    long t3 = System.nanoTime();

    Object results = null;
    if (nReturn == 1 || nReturn == 2) {
        // return the components of the result set as strings
        ResultSet rs = parser.getResultSet();
        if (null != rs) {
            HashMap<String, SavableElement> hmComponents = rs.getResults();
            if (nReturn == 2) {
                results = new HashMap<String, SavableElement>();
                Iterator<String> it = hmComponents.keySet().iterator();
                while (it.hasNext()) {
                    String sKey = it.next();
                    ((HashMap<String, SavableElement>) results).put(new String(sKey), hmComponents.get(sKey));
                }
            } else {
                results = new String[hmComponents.size()];
                Iterator<String> it = hmComponents.keySet().iterator();

                int i = 0;
                while (it.hasNext()) {
                    SavableElement objElement = hmComponents.get(it.next());
                    if (null != objElement) {
                        ((String[]) results)[i++] = objElement.toString();
                    }
                }
            }
        }
    } else if (nReturn == 3) {
        ResultSet rs = parser.getResultSet();
        results = new HashSet<JSONObject>();

        if (null != rs) {
            HashMap<String, SavableElement> hmComponents = rs.getResults();

            // pigeonize every device
            Iterator<String> it = hmComponents.keySet().iterator();

            while (it.hasNext()) {

                SavableElement se = hmComponents.get(it.next());
                if (se instanceof DeviceArray) {
                    int nSize = ((DeviceArray) se).size();
                    for (int i = 0; i < nSize; i++) {
                        try {
                            JSONObject json;
                            Device device = (Device) ((DeviceArray) se).get(i);
                            json = Eugene2JSON.toJSON(device);
                            json.put("pigeon-uri", Pigeon.visualize(device));
                            ((HashSet<JSONObject>) results).add(json);

                            System.out.println("pigeon-uri: " + Pigeon.visualize(device));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    long t4 = System.nanoTime();
    // clean up the symbol tables
    parser.cleanUpNoExit();

    long t5 = System.nanoTime();

    //      System.out.println("start-up time: "+((t2-t1)*Math.pow(10, -9))+"sec");
    //      System.out.println("execution time: "+((t3-t2)*Math.pow(10, -9))+"sec");
    //      System.out.println("result processing time: "+((t4-t3)*Math.pow(10, -9))+"sec");
    //      System.out.println("clean-up time: "+((t5-t4)*Math.pow(10, -9))+"sec");

    return results;
}

From source file:com.omertron.rottentomatoesapi.TestLogger.java

/**
 * Configure the logger with a simple in-memory file for the required log level
 *
 * @param level The logging level required
 * @return True if successful//  www. j a v a2 s . com
 */
public static boolean Configure(String level) {
    StringBuilder config = new StringBuilder("handlers = java.util.logging.ConsoleHandler\n");
    config.append(".level = ").append(level).append(CRLF);
    config.append("java.util.logging.ConsoleHandler.level = ").append(level).append(CRLF);
    // Only works with Java 7 or later
    config.append("java.util.logging.SimpleFormatter.format = [%1$tH:%1$tM:%1$tS %4$6s] %2$s - %5$s %6$s%n")
            .append(CRLF);
    // Exclude logging messages
    // Note: This does not work for apache
    config.append("org.apache.http.level = SEVERE").append(CRLF);

    InputStream ins = new ByteArrayInputStream(config.toString().getBytes());
    try {
        LogManager.getLogManager().readConfiguration(ins);
        // Exclude http logging
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "warn");

    } catch (IOException ex) {
        LOG.warn("Failed to configure log manager due to an IO problem", ex);
        return Boolean.FALSE;
    } finally {
        try {
            ins.close();
        } catch (IOException ex) {
            LOG.info("Failed to close input stream", ex);
        }
    }
    LOG.debug("Logger initialized to '{}' level", level);
    return Boolean.TRUE;
}

From source file:com.ning.metrics.action.binder.filters.SetupJULBridge.java

@Override
public void contextInitialized(final ServletContextEvent event) {
    // we first remove the default handler(s)
    final Logger rootLogger = LogManager.getLogManager().getLogger("");
    final Handler[] handlers = rootLogger.getHandlers();

    if (!ArrayUtils.isEmpty(handlers)) {
        for (Handler handler : handlers) {
            rootLogger.removeHandler(handler);
        }/*from   www .  j a v a  2  s  . co  m*/
    }
    // and then we let jul-to-sfl4j do its magic so that jersey messages go to sfl4j (and thus log4j)
    SLF4JBridgeHandler.install();

    log.info("Assimilated java.util Logging");
}

From source file:com.ning.metrics.collector.endpoint.setup.SetupJULBridge.java

@Override
public void contextInitialized(final ServletContextEvent event) {
    // we first remove the default handler(s)
    final Logger rootLogger = LogManager.getLogManager().getLogger("");
    final Handler[] handlers = rootLogger.getHandlers();

    if (!ArrayUtils.isEmpty(handlers)) {
        for (final Handler handler : handlers) {
            rootLogger.removeHandler(handler);
        }/*from  w ww.j  av  a  2s  .c  o m*/
    }
    // and then we let jul-to-sfl4j do its magic so that jersey messages go to sfl4j (and thus log4j)
    SLF4JBridgeHandler.install();

    log.info("Assimilated java.util Logging");
}

From source file:com.omertron.fanarttvapi.TestLogger.java

/**
 * Configure the logger with a simple in-memory file for the required log
 * level//  w  ww.  j  ava  2  s.  c o  m
 *
 * @param level The logging level required
 * @return True if successful
 */
public static boolean Configure(String level) {
    StringBuilder config = new StringBuilder("handlers = java.util.logging.ConsoleHandler\n");
    config.append(".level = ").append(level).append(CRLF);
    config.append("java.util.logging.ConsoleHandler.level = ").append(level).append(CRLF);
    // Only works with Java 7 or later
    config.append("java.util.logging.SimpleFormatter.format = [%1$tH:%1$tM:%1$tS %4$6s] %2$s - %5$s %6$s%n")
            .append(CRLF);
    // Exclude logging messages
    config.append("org.apache.http.level = SEVERE").append(CRLF);

    InputStream ins = new ByteArrayInputStream(config.toString().getBytes());
    try {
        LogManager.getLogManager().readConfiguration(ins);
        // Exclude http logging
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "warn");

    } catch (IOException ex) {
        LOG.warn("Failed to configure log manager due to an IO problem", ex);
        return Boolean.FALSE;
    } finally {
        try {
            ins.close();
        } catch (IOException ex) {
            LOG.info("Failed to close input stream", ex);
        }
    }
    LOG.debug("Logger initialized to '{}' level", level);
    return Boolean.TRUE;
}

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

    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.xframium.device.logging.ThreadedFileHandler.java

public void configureHandler(Level baseLevel) {
    setLevel(baseLevel);/* w  w  w . jav  a  2 s .  co  m*/
    setFormatter(new SimpleFormatter());

    LogManager.getLogManager().getLogger("").addHandler(this);
    LogManager.getLogManager().getLogger("").setLevel(baseLevel);
    if (LogManager.getLogManager().getLogger(X_NAMESPACE) != null) {
        LogManager.getLogManager().getLogger(X_NAMESPACE).setLevel(baseLevel);
        LogManager.getLogManager().getLogger(X_NAMESPACE).addHandler(this);
    }
}

From source file:com.moviejukebox.TestLogger.java

/**
 * configure the logger with a simple in-memory file for the required log level
 *
 * @param level The logging level required
 * @return True if successful//from   w  w  w  . j  av a 2s  . c o  m
 */
public static boolean configure(String level) {
    StringBuilder config = new StringBuilder("handlers = java.util.logging.ConsoleHandler\n");
    config.append(".level = ").append(level).append(CRLF);
    config.append("java.util.logging.ConsoleHandler.level = ").append(level).append(CRLF);
    // Only works with Java 7 or later
    config.append("java.util.logging.SimpleFormatter.format = [%1$tH:%1$tM:%1$tS %4$6s] %2$s - %5$s %6$s%n")
            .append(CRLF);
    // Exclude http logging
    config.append("sun.net.www.protocol.http.HttpURLConnection.level = OFF").append(CRLF);
    config.append("org.apache.http.level = SEVERE").append(CRLF);

    try (InputStream ins = new ByteArrayInputStream(config.toString().getBytes())) {
        LogManager.getLogManager().readConfiguration(ins);
    } catch (IOException e) {
        LOG.warn("Failed to configure log manager due to an IO problem", e);
        return Boolean.FALSE;
    }
    LOG.debug("Logger initialized to '{}' level", level);
    return Boolean.TRUE;
}

From source file:org.eclipse.ecr.common.logging.JavaUtilLoggingHelper.java

/**
 * Resets {@code java.util.logging} redirections.
 *///  ww w  .j  a v  a2  s  .  co m
public static synchronized void reset() {
    if (activeHandler == null) {
        return;
    }
    try {
        Logger rootLogger = LogManager.getLogManager().getLogger("");
        rootLogger.removeHandler(activeHandler);
    } catch (Exception e) {
        log.error("Handler removal failed", e);
    }
    activeHandler = null;
}

From source file:com.github.nethad.clustermeister.provisioning.cli.ProvisioningCLI.java

private static void loadJDKLoggingConfiguration() {
    try {/* ww  w.j av a  2  s .co m*/
        LogManager.getLogManager()
                .readConfiguration(ProvisioningCLI.class.getResourceAsStream("/jdk-logging.properties"));
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (SecurityException ex) {
        ex.printStackTrace();
    }
}