List of usage examples for java.util.logging ConsoleHandler setFormatter
public synchronized void setFormatter(Formatter newFormatter) throws SecurityException
From source file:lineage.LineageEngine.java
public static void main(String[] args) { Options options = new Options(); // Commands/*from w ww .j a v a2s . co m*/ options.addOption("build", false, "Construct the sample lineage trees"); // Input/Output/Display options.addOption("i", true, "Input file path [required]"); options.addOption("o", true, "Output file path (default: input file with suffix .trees.txt)"); options.addOption("cp", false, "Input data represents cell prevalaence (CP) values"); options.addOption("sampleProfile", false, "Input file contains the SSNV sample presence-absence profile (this will disable the default SSNV calling step)"); options.addOption("n", "normal", true, "Normal sample column id in the list of samples, 0-based (e.g 0 is the first column) [required without -sampleProfile]"); options.addOption("clustersFile", true, "SSNV clusters file path"); options.addOption("s", "save", true, "Maximum number of output trees to save (default: 1)"); options.addOption("showNetwork", "net", false, "Display the constraint network"); options.addOption("showTree", "tree", true, "Number of top-ranking trees to display (default: 0)"); // SSNV filtering / calling options.addOption("maxVAFAbsent", "absent", true, "Maximum VAF to robustly consider an SSNV as absent from a sample [required without -sampleProfile]"); options.addOption("minVAFPresent", "present", true, "Minimum VAF to robustly consider an SSNV as present in a sample [required without -sampleProfile]"); options.addOption("maxVAFValid", true, "Maximum allowed VAF in a sample (default: 0.6)"); options.addOption("minProfileSupport", true, "Minimum number of robust SSNVs required for a group presence-absence profile to be labeled robust (default: 2)"); // Network Construction / Tree Search options.addOption("minClusterSize", true, "Minimum size a cluster must have to be a considered a node in the network (default: 2)"); options.addOption("minPrivateClusterSize", true, "Minimum size a private mutation cluster must have to be a considered a node in the network (default: 1)"); options.addOption("minRobustNodeSupport", true, "Minimum number of robust SSNVs required for a node to be labeled robust during tree search: non-robust nodes can be removed from the network when no valid lineage trees are found (default: 2)"); options.addOption("maxClusterDist", true, "Maximum mean VAF difference up to which two clusters can be collapsed (default: 0.2)"); options.addOption("c", "completeNetwork", false, "Add all possible edges to the constraint network (default: private nodes are connected only to closest level parents; only nodes with no other parents are descendants of root)"); options.addOption("e", true, "VAF error margin (default: 0.1)"); options.addOption("nTreeQPCheck", true, "Number of top-ranking trees on which the QP consistency check is run, we have not seen this check fail in practice (default: 0, for best performance)"); options.addOption("v", "verbose", false, "Verbose mode"); options.addOption("h", "help", false, "Print usage"); // display order ArrayList<Option> optionsList = new ArrayList<Option>(); optionsList.add(options.getOption("build")); optionsList.add(options.getOption("i")); optionsList.add(options.getOption("o")); optionsList.add(options.getOption("cp")); optionsList.add(options.getOption("sampleProfile")); optionsList.add(options.getOption("n")); optionsList.add(options.getOption("clustersFile")); optionsList.add(options.getOption("s")); optionsList.add(options.getOption("net")); optionsList.add(options.getOption("tree")); optionsList.add(options.getOption("maxVAFAbsent")); optionsList.add(options.getOption("minVAFPresent")); optionsList.add(options.getOption("maxVAFValid")); optionsList.add(options.getOption("minProfileSupport")); optionsList.add(options.getOption("minClusterSize")); optionsList.add(options.getOption("minPrivateClusterSize")); optionsList.add(options.getOption("minRobustNodeSupport")); optionsList.add(options.getOption("maxClusterDist")); optionsList.add(options.getOption("c")); optionsList.add(options.getOption("e")); optionsList.add(options.getOption("nTreeQPCheck")); optionsList.add(options.getOption("v")); optionsList.add(options.getOption("h")); CommandLineParser parser = new BasicParser(); CommandLine cmdLine = null; HelpFormatter hf = new HelpFormatter(); hf.setOptionComparator(new OptionComarator<Option>(optionsList)); try { cmdLine = parser.parse(options, args); } catch (ParseException e) { System.out.println(e.getMessage()); hf.printHelp("lichee", options); System.exit(-1); } // Set-up input args Args params = new Args(); if (cmdLine.hasOption("i")) { params.inputFileName = cmdLine.getOptionValue("i"); } else { System.out.println("Required parameter: input file path [-i]"); hf.printHelp("lichee", options); System.exit(-1); } if (cmdLine.hasOption("o")) { params.outputFileName = cmdLine.getOptionValue("o"); } else { params.outputFileName = params.inputFileName + TREES_TXT_FILE_EXTENSION; } if (cmdLine.hasOption("clustersFile")) { params.clustersFileName = cmdLine.getOptionValue("clustersFile"); } if (cmdLine.hasOption("sampleProfile")) { Parameters.INPUT_FORMAT = Format.SNV_WITH_PROFILE; } if (cmdLine.hasOption("n")) { params.normalSampleId = Integer.parseInt(cmdLine.getOptionValue("n")); } else if (!cmdLine.hasOption("sampleProfile")) { System.out.println("Required parameter: normal sample id [-n]"); hf.printHelp("lichee", options); System.exit(-1); } if (cmdLine.hasOption("showTree")) { params.numShow = Integer.parseInt(cmdLine.getOptionValue("showTree")); } if (cmdLine.hasOption("showNetwork")) { params.showNetwork = true; } if (cmdLine.hasOption("s")) { params.numSave = Integer.parseInt(cmdLine.getOptionValue("s")); } if (cmdLine.hasOption("maxVAFAbsent")) { Parameters.MAX_VAF_ABSENT = Double.parseDouble(cmdLine.getOptionValue("maxVAFAbsent")); } else if (!cmdLine.hasOption("sampleProfile")) { System.out.println("Required parameter: -maxVAFAbsent"); hf.printHelp("lichee", options); System.exit(-1); } if (cmdLine.hasOption("minVAFPresent")) { Parameters.MIN_VAF_PRESENT = Double.parseDouble(cmdLine.getOptionValue("minVAFPresent")); } else if (!cmdLine.hasOption("sampleProfile")) { System.out.println("Required parameter: -minVAFPresent"); hf.printHelp("lichee", options); System.exit(-1); } if (cmdLine.hasOption("maxVAFValid")) { Parameters.MAX_ALLOWED_VAF = Double.parseDouble(cmdLine.getOptionValue("maxVAFValid")); } if (cmdLine.hasOption("minProfileSupport")) { Parameters.MIN_GROUP_PROFILE_SUPPORT = Integer.parseInt(cmdLine.getOptionValue("minProfileSupport")); } if (cmdLine.hasOption("minClusterSize")) { Parameters.MIN_CLUSTER_SIZE = Integer.parseInt(cmdLine.getOptionValue("minClusterSize")); } if (cmdLine.hasOption("minPrivateClusterSize")) { Parameters.MIN_PRIVATE_CLUSTER_SIZE = Integer.parseInt(cmdLine.getOptionValue("minPrivateClusterSize")); } if (cmdLine.hasOption("minRobustNodeSupport")) { Parameters.MIN_ROBUST_CLUSTER_SUPPORT = Integer .parseInt(cmdLine.getOptionValue("minRobustNodeSupport")); } if (cmdLine.hasOption("maxClusterDist")) { Parameters.MAX_COLLAPSE_CLUSTER_DIFF = Double.parseDouble(cmdLine.getOptionValue("maxClusterDist")); } if (cmdLine.hasOption("c")) { Parameters.ALL_EDGES = true; } if (cmdLine.hasOption("cp")) { Parameters.CP = true; Parameters.VAF_MAX = 1.0; Parameters.MAX_ALLOWED_VAF = 1.0; } if (cmdLine.hasOption("e")) { Parameters.VAF_ERROR_MARGIN = Double.parseDouble(cmdLine.getOptionValue("e")); } if (cmdLine.hasOption("nTreeQPCheck")) { Parameters.NUM_TREES_FOR_CONSISTENCY_CHECK = Integer.parseInt(cmdLine.getOptionValue("nTreeQPCheck")); } if (cmdLine.hasOption("h")) { new HelpFormatter().printHelp(" ", options); } // logger ConsoleHandler h = new ConsoleHandler(); h.setFormatter(new LogFormatter()); h.setLevel(Level.INFO); logger.setLevel(Level.INFO); if (cmdLine.hasOption("v")) { h.setLevel(Level.FINEST); logger.setLevel(Level.FINEST); } logger.addHandler(h); logger.setUseParentHandlers(false); if (cmdLine.hasOption("build")) { buildLineage(params); } else { new HelpFormatter().printHelp("lichee", options); System.exit(-1); } }
From source file:LineageSimulator.java
public static void main(String[] args) { Options options = new Options(); // commands// w w w.j ava2 s .c o m //options.addOption("simulate", false, "Simulate lineage trees"); //options.addOption("sample", false, "Sample from the simulated trees"); //options.addOption("evaluate", false, "Evaluate trees"); // tree simulation options.addOption("t", "nTrees", true, "Number of trees to simulate (default: 100)"); options.addOption("i", "nIter", true, "Number of tree growth iterations (default: 50)"); options.addOption("snv", "probSNV", true, "Per node probablity of generating a descendant cell population with an acquired SNV during a tree growth iteration (default: 0.15)"); options.addOption("cnv", "probCNV", true, "Per node probablity of generating a descendant cell population with an acquired CNV during a tree growth iteration (default: 0.02)"); options.addOption("probDeath", true, "Probablity of a cell population death in each tree growth iteration (default: 0.06)"); options.addOption("maxPopulationSize", true, "Max size of a cell population (default: 1000000)"); options.addOption("minNodes", true, "Minimum number of undead cell population nodes in a valid tree, tree growth will continue beyond the defined number of iterations until this value is reached (default: 10)"); options.addOption("maxNodes", true, "Maximum number of undead cell population nodes in a tree, tree growth will stop after the iteration in which this value is reached/first surpassed (default: 1000)"); // sampling Option samplesOption = new Option("s", "nSamples", true, "Number of samples to collect, accepts multiple values, e.g. 5 10 15 (default: 5)"); samplesOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(samplesOption); Option covOption = new Option("c", "coverage", true, "Simulated coverage to generate the VAFs, accepts multiple values, e.g. 500 1000 (default: 1000)"); covOption.setArgs(Option.UNLIMITED_VALUES); options.addOption(covOption); options.addOption("maxSubclones", true, "Max number of subclones per sample (default: 5)"); options.addOption("sampleSize", true, "Number of cells per sample (default: 100000)"); options.addOption("e", true, "Sequencing error (default: 0.001)"); options.addOption("minNC", true, "Minimum percentage of normal contamination per sample; the percentage will be randomly generated from the range [minNC maxNC] for each sample (default: 0)"); options.addOption("maxNC", true, "Maximum percentage of normal contamination per sample; if maxNC < minNC, maxNC will be automatically set to minNC; the percentage will be randomly generated from the range [minNC maxNC] for each sample (default: 20)"); //options.addOption("localized", false, "Enable localized sampling (default: random sampling)"); //options.addOption("mixSubclone", false, "With localized sampling, add an additional subclone from a different subtree to each sample; by default, the sample is localized to a single disjoint subtree"); // input/output/display options.addOption("dir", "outputDir", true, "Directory where the output files should be created [required]"); options.addOption("dot", false, "Produce DOT files for the simulated trees"); options.addOption("sdot", "sampledDot", false, "Produce DOT files for the simulated trees with indicated samples"); options.addOption("sampleProfile", false, "Output VAF file includes an additional column with the binary sample profile for each SNV"); // other options.addOption("v", "verbose", false, "Verbose mode"); options.addOption("h", "help", false, "Print usage"); // display order ArrayList<Option> optionsList = new ArrayList<Option>(); optionsList.add(options.getOption("dir")); optionsList.add(options.getOption("t")); optionsList.add(options.getOption("i")); optionsList.add(options.getOption("snv")); optionsList.add(options.getOption("cnv")); optionsList.add(options.getOption("probDeath")); optionsList.add(options.getOption("maxPopulationSize")); optionsList.add(options.getOption("minNodes")); optionsList.add(options.getOption("maxNodes")); optionsList.add(options.getOption("s")); optionsList.add(options.getOption("c")); optionsList.add(options.getOption("maxSubclones")); optionsList.add(options.getOption("sampleSize")); optionsList.add(options.getOption("e")); optionsList.add(options.getOption("minNC")); optionsList.add(options.getOption("maxNC")); optionsList.add(options.getOption("dot")); optionsList.add(options.getOption("sdot")); optionsList.add(options.getOption("sampleProfile")); optionsList.add(options.getOption("v")); optionsList.add(options.getOption("h")); CommandLineParser parser = new BasicParser(); CommandLine cmdLine = null; HelpFormatter hf = new HelpFormatter(); hf.setOptionComparator(new OptionComarator<Option>(optionsList)); try { cmdLine = parser.parse(options, args); } catch (ParseException e) { System.err.println(e.getMessage()); hf.printHelp(PROG_NAME, options); System.exit(-1); } Args params = new Args(); if (cmdLine.hasOption("dir")) { params.simPath = cmdLine.getOptionValue("dir") + "/" + SIMULATION_DATA_DIR; } else { System.err.println("Required parameter: output directory path [-dir]"); hf.printHelp(PROG_NAME, options); System.exit(-1); } if (cmdLine.hasOption("t")) { Parameters.NUM_TREES = Integer.parseInt(cmdLine.getOptionValue("t")); } if (cmdLine.hasOption("i")) { Parameters.NUM_ITERATIONS = Integer.parseInt(cmdLine.getOptionValue("i")); } if (cmdLine.hasOption("snv")) { Parameters.PROB_SNV = Double.parseDouble(cmdLine.getOptionValue("snv")); } if (cmdLine.hasOption("cnv")) { Parameters.PROB_CNV = Double.parseDouble(cmdLine.getOptionValue("cnv")); } if (cmdLine.hasOption("probDeath")) { Parameters.PROB_DEATH = Double.parseDouble(cmdLine.getOptionValue("probDeath")); } if (cmdLine.hasOption("maxPopulationSize")) { Parameters.MAX_POPULATION_SIZE = Integer.parseInt(cmdLine.getOptionValue("maxPopulationSize")); } if (cmdLine.hasOption("minNodes")) { Parameters.MIN_NUM_NODES = Integer.parseInt(cmdLine.getOptionValue("minNodes")); if (Parameters.MIN_NUM_NODES < 1) { System.err.println("Minimum number of nodes [-minNodes] must be at least 1"); System.exit(-1); } } if (cmdLine.hasOption("maxNodes")) { Parameters.MAX_NUM_NODES = Integer.parseInt(cmdLine.getOptionValue("maxNodes")); if (Parameters.MAX_NUM_NODES < 1 || Parameters.MAX_NUM_NODES < Parameters.MIN_NUM_NODES) { System.err.println( "Maximum number of nodes [-maxNodes] must be at least 1 and not less than [-minNodes]"); System.exit(-1); } } if (cmdLine.hasOption("s")) { String[] samples = cmdLine.getOptionValues("s"); Parameters.NUM_SAMPLES_ARRAY = new int[samples.length]; for (int i = 0; i < samples.length; i++) { Parameters.NUM_SAMPLES_ARRAY[i] = Integer.parseInt(samples[i]); } } if (cmdLine.hasOption("c")) { String[] cov = cmdLine.getOptionValues("c"); Parameters.COVERAGE_ARRAY = new int[cov.length]; for (int i = 0; i < cov.length; i++) { Parameters.COVERAGE_ARRAY[i] = Integer.parseInt(cov[i]); } } if (cmdLine.hasOption("maxSubclones")) { Parameters.MAX_NUM_SUBCLONES = Integer.parseInt(cmdLine.getOptionValue("maxSubclones")); } if (cmdLine.hasOption("sampleSize")) { Parameters.NUM_CELLS_PER_SAMPLE = Integer.parseInt(cmdLine.getOptionValue("sampleSize")); } if (cmdLine.hasOption("e")) { Parameters.SEQUENCING_ERROR = Double.parseDouble(cmdLine.getOptionValue("e")); } if (cmdLine.hasOption("minNC")) { Parameters.MIN_PERCENT_NORMAL_CONTAMINATION = Double.parseDouble(cmdLine.getOptionValue("minNC")); } if (cmdLine.hasOption("maxNC")) { Parameters.MAX_PERCENT_NORMAL_CONTAMINATION = Double.parseDouble(cmdLine.getOptionValue("maxNC")); } if (Parameters.MAX_PERCENT_NORMAL_CONTAMINATION < Parameters.MIN_PERCENT_NORMAL_CONTAMINATION) { Parameters.MAX_PERCENT_NORMAL_CONTAMINATION = Parameters.MIN_PERCENT_NORMAL_CONTAMINATION; } /*if(cmdLine.hasOption("localized")) { Parameters.LOCALIZED_SAMPLING = true; } if(cmdLine.hasOption("mixSubclone")) { Parameters.MIX_NBR_SUBTREE_SUBCLONE = true; }*/ if (cmdLine.hasOption("dot")) { params.generateDOT = true; } if (cmdLine.hasOption("sampledDot")) { params.generateSampledDOT = true; } if (cmdLine.hasOption("sampleProfile")) { params.outputSampleProfile = true; } if (cmdLine.hasOption("h")) { new HelpFormatter().printHelp(" ", options); } // logger ConsoleHandler h = new ConsoleHandler(); h.setFormatter(new LogFormatter()); h.setLevel(Level.INFO); logger.setLevel(Level.INFO); if (cmdLine.hasOption("v")) { h.setLevel(Level.FINEST); logger.setLevel(Level.FINEST); } logger.addHandler(h); logger.setUseParentHandlers(false); // validate settings if (Parameters.PROB_SNV + Parameters.PROB_CNV + Parameters.PROB_DEATH > 1) { System.err.println("The sum of SSNV, CNV, and cell death probabilities cannot exceed 1"); hf.printHelp(PROG_NAME, options); System.exit(-1); } simulateLineageTrees(params); }
From source file:core.PlanC.java
/** * inicio de aplicacion//w ww . j a v a 2 s .c om * * @param arg - argumentos de entrada */ public static void main(String[] args) { // user.name /* * Properties prp = System.getProperties(); System.out.println(getWmicValue("bios", "SerialNumber")); * System.out.println(getWmicValue("cpu", "SystemName")); */ try { // log // -Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n' // System.setProperty("java.util.logging.SimpleFormatter.format", // "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n"); System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %5$s%6$s%n"); FileHandler fh = new FileHandler(LOG_FILE); fh.setFormatter(new SimpleFormatter()); fh.setLevel(Level.INFO); ConsoleHandler ch = new ConsoleHandler(); ch.setFormatter(new SimpleFormatter()); ch.setLevel(Level.INFO); logger = Logger.getLogger(""); Handler[] hs = logger.getHandlers(); for (int x = 0; x < hs.length; x++) { logger.removeHandler(hs[x]); } logger.addHandler(fh); logger.addHandler(ch); // point apache log to this log System.setProperty("org.apache.commons.logging.Log", Jdk14Logger.class.getName()); TPreferences.init(); TStringUtils.init(); Font fo = Font.createFont(Font.TRUETYPE_FONT, TResourceUtils.getFile("Dosis-Light.ttf")); GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fo); fo = Font.createFont(Font.TRUETYPE_FONT, TResourceUtils.getFile("Dosis-Medium.ttf")); GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fo); fo = Font.createFont(Font.TRUETYPE_FONT, TResourceUtils.getFile("AERO_ITALIC.ttf")); GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(fo); SwingTimerTimingSource ts = new SwingTimerTimingSource(); AnimatorBuilder.setDefaultTimingSource(ts); ts.init(); // parse app argument parameters and append to tpreferences to futher uses for (String arg : args) { String[] kv = arg.split("="); TPreferences.setProperty(kv[0], kv[1]); } RUNNING_MODE = TPreferences.getProperty("runningMode", RM_NORMAL); newMsg = Applet.newAudioClip(TResourceUtils.getURL("newMsg.wav")); } catch (Exception e) { SystemLog.logException1(e, true); } // pass icon from metal to web look and feel Icon i1 = UIManager.getIcon("OptionPane.errorIcon"); Icon i2 = UIManager.getIcon("OptionPane.informationIcon"); Icon i3 = UIManager.getIcon("OptionPane.questionIcon"); Icon i4 = UIManager.getIcon("OptionPane.warningIcon"); // Object fcui = UIManager.get("FileChooserUI"); // JFileChooser fc = new JFileChooser(); WebLookAndFeel.install(); // WebLookAndFeel.setDecorateFrames(true); // WebLookAndFeel.setDecorateDialogs(true); UIManager.put("OptionPane.errorIcon", i1); UIManager.put("OptionPane.informationIcon", i2); UIManager.put("OptionPane.questionIcon", i3); UIManager.put("OptionPane.warningIcon", i4); // UIManager.put("TFileChooserUI", fcui); // warm up the IDW. // in my computer, some weird error ocurr if i don't execute this preload. new RootWindow(null); frame = new TWebFrame(); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Exit.shutdown(); } }); if (RUNNING_MODE.equals(RM_NORMAL)) { initEnviorement(); } if (RUNNING_MODE.equals(RM_CONSOLE)) { initConsoleEnviorement(); } if (RUNNING_MODE.equals(ONE_TASK)) { String cln = TPreferences.getProperty("taskName", "*TaskNotFound"); PlanC.logger.log(Level.INFO, "OneTask parameter found in .properties. file Task name = " + cln); try { Class cls = Class.forName(cln); Object dobj = cls.newInstance(); // new class must be extends form AbstractExternalTask TTaskManager.executeTask((Runnable) dobj); return; } catch (Exception e) { PlanC.logger.log(Level.SEVERE, e.getMessage(), e); Exit.shutdown(); } } }
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/*ww w .ja v a 2s . 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); }
From source file:com.bluexml.side.integration.standalone.GenerateModelHelper.java
/** * Init {@link Logger}s associated to package * com.bluexml.side.Integration.standAlone * /*from w w w. ja v a 2 s .c om*/ * @param baseLevel * the level above which logs will be displayed on the console * @return the base {@link Logger} managing the package */ public static Logger initLogger(Level baseLevel) { if (baseLevel == null) { baseLevel = Level.INFO; } if (baseLogger == null) { Logger logger = Logger.getLogger("com.bluexml.side"); // $NON-NLS-1$ ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(new ConsoleSimpleFormatter()); logger.setUseParentHandlers(false); logger.addHandler(handler); baseLogger = logger; consoleHandler = handler; } baseLogger.setLevel(baseLevel); consoleHandler.setLevel(baseLevel); return baseLogger; }
From source file:com.googlecode.jgenhtml.JGenHtmlUtils.java
public static void setLogFormatter(final Logger logger) { logger.setUseParentHandlers(false);//from ww w.j a va 2 s . c o m JGenHtmlLogFormatter formatter = new JGenHtmlLogFormatter(); ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(formatter); logger.addHandler(handler); }
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 ww . j av a2 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:com.frostvoid.trekwar.server.TrekwarServer.java
/** * Initiates logging//from ww w . jav a 2 s . co m * * @throws IOException */ private static void initLogging() throws IOException { FileHandler fh = new FileHandler(galaxyFileName + ".log"); fh.setLevel(LOG.getLevel()); Formatter logFormat = new Formatter() { @Override public String format(LogRecord rec) { StringBuilder buf = new StringBuilder(200); buf.append("#"); buf.append(new java.util.Date()); buf.append(' '); buf.append(rec.getLevel()); buf.append(' '); buf.append(rec.getSourceClassName()).append(".").append(rec.getSourceMethodName()); buf.append(":\n"); buf.append(formatMessage(rec)); buf.append('\n'); return buf.toString(); } }; fh.setFormatter(logFormat); ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(LOG.getLevel()); Formatter conlogFormat = new Formatter() { @Override public String format(LogRecord rec) { StringBuilder buf = new StringBuilder(200); buf.append(rec.getLevel()); buf.append(": "); buf.append(formatMessage(rec)); buf.append('\n'); return buf.toString(); } }; ch.setFormatter(conlogFormat); LOG.addHandler(fh); LOG.addHandler(ch); }
From source file:plugins.GerritTriggerTest.java
@Before public void setUpLogger() { LOGGER.setLevel(Level.ALL);/* www. j a v a 2 s.c o m*/ LOGGER.setUseParentHandlers(false); ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(new SimpleFormatter()); handler.setLevel(Level.ALL); LOGGER.addHandler(handler); }
From source file:org.silverpeas.core.test.rule.CommonAPI4Test.java
public void setLoggerLevel(Level level) { final ConsoleHandler handler = new ConsoleHandler(); setLoggerHandler(handler);/*from ww w . j a v a 2 s . c o m*/ handler.setFormatter(new SimpleFormatter()); switch (level) { case INFO: Logger.getLogger(ROOT_NAMESPACE).setLevel(java.util.logging.Level.INFO); handler.setLevel(java.util.logging.Level.INFO); break; case DEBUG: Logger.getLogger(ROOT_NAMESPACE).setLevel(java.util.logging.Level.FINE); handler.setLevel(java.util.logging.Level.FINE); break; case WARNING: Logger.getLogger(ROOT_NAMESPACE).setLevel(java.util.logging.Level.WARNING); handler.setLevel(java.util.logging.Level.WARNING); break; case ERROR: Logger.getLogger(ROOT_NAMESPACE).setLevel(java.util.logging.Level.SEVERE); handler.setLevel(java.util.logging.Level.SEVERE); break; } }