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: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 v  a 2 s. c om
            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.googlecode.jgenhtml.JGenHtmlUtils.java

public static void setLogFormatter(final Logger logger) {
    logger.setUseParentHandlers(false);//from w  w w.j a  v a2s .c  om
    JGenHtmlLogFormatter formatter = new JGenHtmlLogFormatter();
    ConsoleHandler handler = new ConsoleHandler();
    handler.setFormatter(formatter);
    logger.addHandler(handler);
}

From source file:org.openstreetmap.josm.data.cache.JCSCacheManager.java

@SuppressWarnings("resource")
private static void initialize() throws IOException {
    File cacheDir = new File(Main.pref.getCacheDirectory(), "jcs");

    if (!cacheDir.exists() && !cacheDir.mkdirs())
        throw new IOException("Cannot access cache directory");

    File cacheDirLockPath = new File(cacheDir, ".lock");
    if (!cacheDirLockPath.exists() && !cacheDirLockPath.createNewFile()) {
        LOG.log(Level.WARNING, "Cannot create cache dir lock file");
    }/* w  w  w .jav  a 2  s.  c  om*/
    cacheDirLock = new FileOutputStream(cacheDirLockPath).getChannel().tryLock();

    if (cacheDirLock == null)
        LOG.log(Level.WARNING, "Cannot lock cache directory. Will not use disk cache");

    // raising logging level gives ~500x performance gain
    // http://westsworld.dk/blog/2008/01/jcs-and-performance/
    final Logger jcsLog = Logger.getLogger("org.apache.commons.jcs");
    jcsLog.setLevel(Level.INFO);
    jcsLog.setUseParentHandlers(false);
    // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level
    Arrays.stream(jcsLog.getHandlers()).forEach(jcsLog::removeHandler);
    jcsLog.addHandler(new Handler() {
        final SimpleFormatter formatter = new SimpleFormatter();

        @Override
        public void publish(LogRecord record) {
            String msg = formatter.formatMessage(record);
            if (record.getLevel().intValue() >= Level.SEVERE.intValue()) {
                Logging.error(msg);
            } else if (record.getLevel().intValue() >= Level.WARNING.intValue()) {
                Logging.warn(msg);
                // downgrade INFO level to debug, as JCS is too verbose at INFO level
            } else if (record.getLevel().intValue() >= Level.INFO.intValue()) {
                Logging.debug(msg);
            } else {
                Logging.trace(msg);
            }
        }

        @Override
        public void flush() {
            // nothing to be done on flush
        }

        @Override
        public void close() {
            // nothing to be done on close
        }
    });

    // this could be moved to external file
    Properties props = new Properties();
    // these are default common to all cache regions
    // use of auxiliary cache and sizing of the caches is done with giving proper geCache(...) params
    // CHECKSTYLE.OFF: SingleSpaceSeparator
    props.setProperty("jcs.default.cacheattributes", CompositeCacheAttributes.class.getCanonicalName());
    props.setProperty("jcs.default.cacheattributes.MaxObjects", DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString());
    props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker", "true");
    props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put
    props.setProperty("jcs.default.elementattributes", CacheEntryAttributes.class.getCanonicalName());
    props.setProperty("jcs.default.elementattributes.IsEternal", "false");
    props.setProperty("jcs.default.elementattributes.MaxLife", Long.toString(maxObjectTTL));
    props.setProperty("jcs.default.elementattributes.IdleTime", Long.toString(maxObjectTTL));
    props.setProperty("jcs.default.elementattributes.IsSpool", "true");
    // CHECKSTYLE.ON: SingleSpaceSeparator
    CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance();
    cm.configure(props);
    cacheManager = cm;
}

From source file:edu.harvard.iq.dataverse.batch.util.LoggingUtil.java

public static Logger getJobLogger(String jobId) {
    try {/*  w  ww . ja v  a2s .  c o  m*/
        Logger jobLogger = Logger.getLogger("job-" + jobId);
        FileHandler fh;
        String logDir = System.getProperty("com.sun.aas.instanceRoot") + System.getProperty("file.separator")
                + "logs" + System.getProperty("file.separator") + "batch-jobs"
                + System.getProperty("file.separator");
        checkCreateLogDirectory(logDir);
        fh = new FileHandler(logDir + "job-" + jobId + ".log");
        logger.log(Level.INFO, "JOB LOG: " + logDir + "job-" + jobId + ".log");
        jobLogger.addHandler(fh);
        fh.setFormatter(new JobLogFormatter());
        return jobLogger;
    } catch (SecurityException e) {
        logger.log(Level.SEVERE, "Unable to create job logger: " + e.getMessage());
        return null;
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Unable to create job logger: " + e.getMessage());
        return null;
    }
}

From source file:org.spoutcraft.launcher.entrypoint.SpoutcraftLauncher.java

protected static Logger setupLogger() {
    final Logger logger = Utils.getLogger();
    File logDirectory = new File(Utils.getLauncherDirectory(), "logs");
    if (!logDirectory.exists()) {
        logDirectory.mkdir();/*from w  ww .  java  2 s . co m*/
    }
    File logs = new File(logDirectory, "techniclauncher_%D.log");
    RotatingFileHandler fileHandler = new RotatingFileHandler(logs.getPath());

    fileHandler.setFormatter(new TechnicLogFormatter());

    for (Handler h : logger.getHandlers()) {
        logger.removeHandler(h);
    }
    logger.addHandler(fileHandler);

    SpoutcraftLauncher.handler = fileHandler;

    if (params != null && !params.isDebugMode()) {
        logger.setUseParentHandlers(false);

        System.setOut(new PrintStream(new LoggerOutputStream(console, Level.INFO, logger), true));
        System.setErr(new PrintStream(new LoggerOutputStream(console, Level.SEVERE, logger), true));
    }

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.log(Level.SEVERE, "Unhandled Exception in " + t, e);

            if (errorDialog == null) {
                LauncherFrame frame = null;

                try {
                    frame = Launcher.getFrame();
                } catch (Exception ex) {
                    //This can happen if we have a very early crash- before Launcher initializes
                }

                errorDialog = new ErrorDialog(frame, e);
                errorDialog.setVisible(true);
            }
        }
    });

    return logger;
}

From source file:org.openqa.selenium.server.log.LoggingManager.java

private static File addNewSeleniumFileHandler(Logger currentLogger, RemoteControlConfiguration configuration) {
    try {//from   w  w  w . jav a 2 s.  co  m
        FileHandler fileHandler;
        final File logFile;

        logFile = configuration.getLogOutFile();
        fileHandler = seleniumFileHandlers.get(logFile);
        if (fileHandler == null) {
            fileHandler = registerNewSeleniumFileHandler(logFile);
        }
        fileHandler.setFormatter(new TerseFormatter(true));
        currentLogger.setLevel(Level.FINE);
        fileHandler.setLevel(Level.FINE);
        currentLogger.addHandler(fileHandler);
        return logFile;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openqa.selenium.server.log.LoggingManager.java

private static void addPerSessionLogger(Logger logger, RemoteControlConfiguration configuration,
        boolean debugMode) {
    if (debugMode) {
        perSessionLogHandler = new DefaultPerSessionLogHandler(configuration.shortTermMemoryLoggerCapacity(),
                Level.FINE, new TerseFormatter(true), configuration.isCaptureOfLogsOnQuitEnabled());
    } else {/*ww  w . j  a  v  a  2  s.  c  om*/
        perSessionLogHandler = new DefaultPerSessionLogHandler(configuration.shortTermMemoryLoggerCapacity(),
                Level.INFO, new TerseFormatter(true), configuration.isCaptureOfLogsOnQuitEnabled());
    }
    logger.addHandler(perSessionLogHandler);
}

From source file:dk.hippogrif.prettyxml.PrettyPrint.java

static String loadConfiguration(String resource) {
    try {//  ww  w  . ja v a  2  s. com
        Properties prop = loadPropertiesResource(resource);

        // logging
        String loggingLevel = prop.getProperty("logging.Level");
        if (loggingLevel != null) {
            Level level = Level.parse(loggingLevel);
            Logger l = Logger.getLogger("dk.hippogrif.prettyxml");
            l.setLevel(level);
            if ("ConsoleHandler".equals(prop.getProperty("logging.Handler"))) {
                ConsoleHandler h = new ConsoleHandler();
                h.setLevel(level);
                l.addHandler(h);
            } else if ("FileHandler".equals(prop.getProperty("logging.Handler"))) {
                FileHandler h = new FileHandler(System.getProperty("user.home") + "/prettyxml.log");
                h.setLevel(level);
                l.addHandler(h);
            }
            logger.config("logging.Level=" + loggingLevel);
        }

        // version
        version = prop.getProperty("version", "");
        logger.config("version=" + version);

        // wellknown encodings
        String s = prop.getProperty("encodings");
        if (s == null) {
            throw new Exception("encodings missing in prettyxml.properties");
        }
        encodings = s.split(";");

        // wellknown property settings
        s = prop.getProperty("settings");
        if (s == null) {
            throw new Exception("settings missing in prettyxml.properties");
        }
        settings = s.split(";");
        setting = new HashMap();
        for (int i = 0; i < settings.length; i++) {
            String name = settings[i];
            Properties props = loadPropertiesResource(name + ".properties");
            checkProperties(props, false);
            setting.put(name, props);
        }

        // wellknown transformations
        s = prop.getProperty("transformations");
        if (s == null) {
            throw new Exception("transformations missing in prettyxml.properties");
        }
        transformations = s.split(";");
        transformation = new HashMap();
        for (int i = 0; i < transformations.length; i++) {
            String name = transformations[i];
            transformation.put(name, mkTransformerResource(name + ".xslt"));
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return version;
}

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);
    }//from w w  w  .  j  a  va 2 s. co 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.noroomattheinn.utils.Utils.java

public static void setupLogger(File where, String basename, Logger logger, Level level) {
    rotateLogs(where, basename, 3);/*from www. j  a v  a  2 s. c om*/

    FileHandler fileHandler;
    try {
        logger.setLevel(level);
        fileHandler = new FileHandler((new File(where, basename + "-00.log")).getAbsolutePath());
        fileHandler.setFormatter(new SimpleFormatter());
        fileHandler.setLevel(level);
        logger.addHandler(fileHandler);

        for (Handler handler : Logger.getLogger("").getHandlers()) {
            if (handler instanceof ConsoleHandler) {
                handler.setLevel(level);
            }
        }
    } catch (IOException | SecurityException ex) {
        logger.severe("Unable to establish log file: " + ex);
    }
}