Example usage for java.util.logging FileHandler FileHandler

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

Introduction

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

Prototype

public FileHandler(String pattern, long limit, int count, boolean append) throws IOException 

Source Link

Document

Initialize a FileHandler to write to a set of files with optional append.

Usage

From source file:org.azrul.langmera.DecisionService.java

public static void main(String[] args) throws IOException {
    ConfigurationProvider config = null;
    ConfigFilesProvider configFilesProvider = () -> Arrays.asList(Paths.get("config.properties"));
    if (args.length <= 0) {
        ConfigurationSource source = new ClasspathConfigurationSource(configFilesProvider);
        config = new ConfigurationProviderBuilder().withConfigurationSource(source).build();
    } else {/*from   w ww .j  ava2  s.c o m*/
        ConfigurationSource source = new FilesConfigurationSource(configFilesProvider);
        Environment environment = new ImmutableEnvironment(args[0]);
        config = new ConfigurationProviderBuilder().withConfigurationSource(source).withEnvironment(environment)
                .build();

    }
    Logger logger = null;
    if (config.getProperty("log.file", String.class).isEmpty() == false) {
        FileHandler logHandler = new FileHandler(config.getProperty("log.file", String.class),
                config.getProperty("log.sizePerFile", Integer.class) * 1024 * 1024,
                config.getProperty("log.maxFileCount", Integer.class), true);
        logHandler.setFormatter(new SimpleFormatter());
        logHandler.setLevel(Level.INFO);

        Logger rootLogger = Logger.getLogger("");
        rootLogger.removeHandler(rootLogger.getHandlers()[0]);
        logHandler.setLevel(Level.parse(config.getProperty("log.level", String.class)));
        rootLogger.setLevel(Level.parse(config.getProperty("log.level", String.class)));
        rootLogger.addHandler(logHandler);

        logger = rootLogger;
    } else {
        logger = Logger.getGlobal();
    }

    VertxOptions options = new VertxOptions();
    options.setMaxEventLoopExecuteTime(Long.MAX_VALUE);
    options.setWorkerPoolSize(config.getProperty("workerPoolSize", Integer.class));
    options.setEventLoopPoolSize(40);

    Vertx vertx = Vertx.vertx(options);
    vertx.deployVerticle(new DecisionService(logger, config));
    vertx.deployVerticle(new SaveToDB(logger, config));

}

From source file:havocx42.Program.java

private static void initRootLogger() throws SecurityException, IOException {

    FileHandler fileHandler;/*  w w w.  j ava2 s  .  c  om*/
    fileHandler = new FileHandler("PRWeaponStats.%u.%g.txt", 1024 * 1024 * 8, 3, false);
    fileHandler.setLevel(Level.FINEST);
    fileHandler.setFormatter(new SimpleFormatter());
    Logger rootLogger = Logger.getLogger("");
    Handler[] handlers = rootLogger.getHandlers();
    for (Handler handler : handlers) {
        handler.setLevel(Level.INFO);
    }
    rootLogger.setLevel(Level.FINEST);
    rootLogger.addHandler(fileHandler);
}

From source file:com.screenslicer.common.Log.java

public static void init(String loggerName, boolean allowFileLogging) {
    logger = Logger.getLogger(loggerName);
    if (allowFileLogging) {
        FileHandler fh = null;//from ww  w .  ja  v a 2  s.  c o m
        try {
            fh = new FileHandler("../" + loggerName + ".log", 250000, 9, true);
            logger.addHandler(fh);
            String logLevel = System.getProperty("screenslicer-logging", "prod");
            if (logLevel.equals("prod")) {
                logger.setLevel(Level.INFO);
            } else if (logLevel.equals("debug")) {
                logger.setLevel(Level.ALL);
            }
            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);
        } catch (Throwable t) {
            t.printStackTrace();
            throw new RuntimeException(t);
        }
    }
}

From source file:regextester.RegexTester.java

public RegexTester() throws Exception {
    RegexTester.application = this;

    // First setup our logger
    this.checkSettingsDirExists();
    logger.setLevel(Level.SEVERE);
    FileHandler fh = new FileHandler(this.settingsDirname + File.separator + "debug.log", 8096, 1, true);
    logger.addHandler(fh);/* w w w .  j a va2  s.c o  m*/
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);
    logger.info("Starting RegexTester");

    // Load our properties and attach the database, creating it if it doesn't exist
    this.loadProperties();

    // Create our GUI
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    window = new MainWindow(this);
    window.setLocationRelativeTo(null);
    window.setTitle("RegexTester");
    window.setVisible(true);
}

From source file:org.peercast.core.PeerCastApplication.java

private void installLogHandlers() {
    //        org.seamless.util.logging.LoggingUtil.resetRootHandler(
    //                new FixedAndroidLogHandler()
    //        );/*from ww w . j av  a2  s  . co  m*/
    Logger appLogger = Logger.getLogger(getPackageName());
    appLogger.setLevel(Level.FINEST);

    try {
        Logger rootLogger = Logger.getLogger("");
        rootLogger.setLevel(Level.INFO);

        String pat = getCacheDir().getAbsolutePath() + "/app%g.log";
        FileHandler handler = new FileHandler(pat, MAX_LOG_SIZE, 1, true);

        handler.setFormatter(new CsvFormatter());
        rootLogger.addHandler(handler);
    } catch (IOException e) {
        Log.e(TAG, "new FileHandler()", e);
    }
}

From source file:namedatabasescraper.NameDatabaseScraper.java

public NameDatabaseScraper() throws Exception {
    NameDatabaseScraper.application = this;

    // First setup our logger
    this.checkSettingsDirExists();
    logger.setLevel(Level.INFO);// www  .j av  a  2 s . c  o  m
    FileHandler fh = new FileHandler(this.settingsDirname + File.separator + "debug.log", 8096, 1, false);
    logger.addHandler(fh);
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);
    logger.info("Starting NameDatabaseScraper");

    // Load our properties and attach the database, creating it if it doesn't exist
    this.loadProperties();
    this.attachDatabase();

    // Create our GUI
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    window = new MainWindow(this);
    window.setLocationRelativeTo(null);
    window.setTitle("NameDatabaseScraper");
    window.setVisible(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);
    }/*from   www  .j a  v a  2 s . 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:io.stallion.services.Log.java

/**
 * Start logging to the file defined by "logFile" in settings files
 *//*from   ww  w  .  j av  a2 s.co m*/
public static void enableFileLogger() {
    logger.removeHandler(handler);
    handler.close();
    String logPath = Settings.instance().getLogFile();
    if (!new File(logPath).getParentFile().isDirectory()) {
        new File(logPath).getParentFile().mkdirs();
    }
    try {
        fileHandler = new FileHandler(logPath, 50000000, 7, true);
    } catch (IOException e) {
        throw new ConfigException("Invalid log file path: " + logPath);
    }
    fileHandler.setFormatter(new LogFormatter());
    handler.setLevel(logger.getLevel());
    logger.addHandler(fileHandler);
    System.out.println("----->  Logging to file " + logPath + " at level " + logger.getLevel() + " ---->");
}

From source file:com.pivotal.gemfire.tools.pulse.internal.log.PulseLogWriter.java

private PulseLogWriter() {
    PulseConfig pulseConfig = Repository.get().getPulseConfig();
    // Create Logger
    logger = Logger.getLogger(this.getClass().getName());

    // Set minimum log level to level passed
    logger.setLevel(pulseConfig.getLogLevel());

    try {/*from  w ww . ja v  a 2  s .c  om*/
        // Get file handler to log messages into log file.
        if (fileHandler == null) {
            fileHandler = new FileHandler(pulseConfig.getLogFileFullName(), pulseConfig.getLogFileSize(),
                    pulseConfig.getLogFileCount(), pulseConfig.getLogAppend());

            // Log Message Formatter
            messageformatter = new MessageFormatter();
            fileHandler.setFormatter(messageformatter);
        }

        // Remove any existing handlers
        // e.g. consoleHandler
        logger.setUseParentHandlers(false);

        // Add File Handler to logger object
        logger.addHandler(fileHandler);
    } catch (SecurityException e) {
        logger.setUseParentHandlers(true);
        e.printStackTrace();
    } catch (IOException e) {
        logger.setUseParentHandlers(true);
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.norvelle.addressdiscoverer.AddressDiscoverer.java

@SuppressWarnings("LeakingThisInConstructor")
public AddressDiscoverer() throws Exception {
    AddressDiscoverer.application = this;

    // First setup our logger. The ORMLite logger is prolix and useless,
    // so we redirect it to a temp file.
    System.setProperty(LocalLog.LOCAL_LOG_FILE_PROPERTY,
            System.getProperty("java.io.tmpdir") + File.separator + "addressdiscoverer.ormlite.log");
    this.checkSettingsDirExists();
    logger.setLevel(Level.SEVERE);
    FileHandler fh = new FileHandler(this.settingsDirname + File.separator + "debug.log", 8096, 1, true);
    logger.addHandler(fh);/*from www.j av  a2s.c  o m*/
    SimpleFormatter formatter = new SimpleFormatter();
    fh.setFormatter(formatter);
    logger.info("Starting AddressDiscoverer");

    // Load our properties and attach the database, creating it if it doesn't exist
    this.loadProperties();
    this.attachDatabase();
    KnownLastName.initialize(this.settingsDirname);
    KnownFirstName.initialize(this.settingsDirname);
    KnownSpanishWord.initialize(this.settingsDirname);
    Abbreviations.initialize(this.settingsDirname);
    GrammarParticles.initialize(this.settingsDirname);
    GenderDeterminer.initialize(this.settingsDirname);

    // Create our GUI
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    window = new MainWindow(this);
    window.setTitle("AddressDiscoverer");
    window.setExtendedState(window.getExtendedState() | java.awt.Frame.MAXIMIZED_BOTH);
    window.setVisible(true);
}