Example usage for java.util.logging ConsoleHandler setLevel

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

Introduction

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

Prototype

public synchronized void setLevel(Level newLevel) throws SecurityException 

Source Link

Document

Set the log level specifying which message levels will be logged by this Handler .

Usage

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  v  a  2s.  c  o m

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

    rootLogger.setLevel(Level.INFO);

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

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

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

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

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

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

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

    System.out.println();

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

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

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

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

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

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

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

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

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

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

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

    String message = "";

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

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

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

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

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

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

    System.out.println(message);

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

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

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

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

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

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

From source file:edu.umass.cs.gigapaxos.PaxosConfig.java

/**
 * @param level/*w w  w. j  a  v a2 s  .  c  om*/
 */
public static void setConsoleHandler(Level level) {
    ConsoleHandler handler = new ConsoleHandler();
    handler.setLevel(level);
    PaxosManager.getLogger().setLevel(level);
    PaxosManager.getLogger().addHandler(handler);
    PaxosManager.getLogger().setUseParentHandlers(false);

    NIOTransport.getLogger().setLevel(level);
    NIOTransport.getLogger().addHandler(handler);
    NIOTransport.getLogger().setUseParentHandlers(false);

}

From source file:org.bonitasoft.engine.api.HTTPServerAPITest.java

@Test(expected = ServerWrappedException.class)
public void invokeMethodCatchUndeclaredThrowableException() throws Exception {
    final PrintStream printStream = System.err;
    final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
    System.setErr(new PrintStream(myOut));
    final Logger logger = Logger.getLogger(HTTPServerAPI.class.getName());
    logger.setLevel(Level.FINE);/*from  ww w. j  a v a 2s  .c  om*/
    final ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(Level.FINE);
    logger.addHandler(ch);

    try {
        final Map<String, Serializable> options = new HashMap<String, Serializable>();
        final String apiInterfaceName = "apiInterfaceName";
        final String methodName = "methodName";
        final List<String> classNameParameters = new ArrayList<String>();
        final Object[] parametersValues = null;

        final HTTPServerAPI httpServerAPI = mock(HTTPServerAPI.class);
        final String response = "response";
        doReturn(response).when(httpServerAPI, "executeHttpPost", eq(options), eq(apiInterfaceName),
                eq(methodName), eq(classNameParameters), eq(parametersValues), Matchers.any(XStream.class));
        doThrow(new UndeclaredThrowableException(new BonitaException("Bonita exception"), "Exception plop"))
                .when(httpServerAPI, "checkInvokeMethodReturn", eq(response), Matchers.any(XStream.class));

        // Let's call it for real:
        doCallRealMethod().when(httpServerAPI).invokeMethod(options, apiInterfaceName, methodName,
                classNameParameters, parametersValues);
        httpServerAPI.invokeMethod(options, apiInterfaceName, methodName, classNameParameters,
                parametersValues);
    } finally {
        System.setErr(printStream);
        final String logs = myOut.toString();
        assertTrue("should have written in logs an exception",
                logs.contains("java.lang.reflect.UndeclaredThrowableException"));
        assertTrue("should have written in logs an exception", logs.contains("BonitaException"));
        assertTrue("should have written in logs an exception", logs.contains("Exception plop"));
    }
}

From source file:plugins.GerritTriggerTest.java

@Before
public void setUpLogger() {
    LOGGER.setLevel(Level.ALL);//from  ww w  .  j  ava  2s.  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   www .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;
    }
}

From source file:majordodo.task.BrokerTestUtils.java

@Before
public void brokerTestUtilsBefore() throws Exception {
    // Setup exception handler
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override/*from  w ww .ja v a2s  .  c o  m*/
        public void uncaughtException(Thread t, Throwable e) {
            System.err.println("uncaughtException from thread " + t.getName() + ": " + e);
            e.printStackTrace();
            unhandledExceptions.add(e);
        }
    });

    // Setup Logger
    System.out.println("Setup logger to level " + logLevel.getName());
    java.util.logging.LogManager.getLogManager().reset();
    ConsoleHandler ch = new ConsoleHandler();
    ch.setLevel(logLevel);
    ch.setFormatter(new Formatter() {
        @Override
        public String format(LogRecord record) {
            return "" + new java.sql.Timestamp(record.getMillis()) + " " + record.getLevel() + " ["
                    + getThreadName(record.getThreadID()) + "<" + record.getThreadID() + ">] "
                    + record.getLoggerName() + ": " + formatMessage(record) + "\n";
        }
    });
    java.util.logging.Logger.getLogger("").setLevel(logLevel);
    java.util.logging.Logger.getLogger("").addHandler(ch);

    // Initialize groupsMap
    groupsMap.clear();
    groupsMap.put(userId, group);

    // Setup workdir
    Path mavenTargetDir = Paths.get("target").toAbsolutePath();
    workDir = Files.createTempDirectory(mavenTargetDir, "test" + System.nanoTime());

    if (startBroker) {
        broker = new Broker(brokerConfig, new FileCommitLog(workDir, workDir, 1024 * 1024),
                new TasksHeap(1000, createTaskPropertiesMapperFunction()));
        broker.startAsWritable();

        server = new NettyChannelAcceptor(broker.getAcceptor());
        server.start();
    }
    if (startReplicatedBrokers) {
        zkServer = new ZKTestEnv(folderZk.getRoot().toPath());
        zkServer.startBookie();

        // Broker 1
        broker1 = new Broker(broker1Config,
                new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(),
                        folderSnapshots.newFolder().toPath(),
                        BrokerHostData.formatHostdata(
                                new BrokerHostData(broker1Host, broker1Port, "", false, null)),
                        false),
                new TasksHeap(1000, createTaskPropertiesMapperFunction()));

        broker1.startAsWritable();

        server1 = new NettyChannelAcceptor(broker1.getAcceptor(), broker1Host, broker1Port);
        server1.start();

        // Broker 2
        broker2 = new Broker(broker2Config,
                new ReplicatedCommitLog(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath(),
                        folderSnapshots.newFolder().toPath(),
                        BrokerHostData.formatHostdata(
                                new BrokerHostData(broker2Host, broker2Port, "", false, null)),
                        false),
                new TasksHeap(1000, createTaskPropertiesMapperFunction()));

        broker2.start();

        server2 = new NettyChannelAcceptor(broker2.getAcceptor(), broker2Host, broker2Port);
        server2.start();

        // Broker locator
        brokerLocator = new ZKBrokerLocator(zkServer.getAddress(), zkServer.getTimeout(), zkServer.getPath());
    }

}

From source file:de.phillme.PhotoSorter.java

private void initLogging() {
    System.setProperty("java.util.logging.SimpleFormatter.format", "%5$s %n");
    LOGGER.setLevel(Level.INFO);//  w  w  w .  j  a  v  a2  s  .  c om
    ConsoleHandler handler = new ConsoleHandler();
    handler.setFormatter(new SimpleFormatter());
    handler.setLevel(Level.INFO);
    LOGGER.addHandler(handler);
    LOGGER.setUseParentHandlers(false);
}

From source file:com.sds.acube.ndisc.mts.xserver.XNDiscServer.java

/**
 *    //w ww  .  j  a  va 2  s .c  om
 * 
 * @throws Exception
 *              ?
 */
private void init() throws Exception {

    /* xsocket  - FINE ???     ?  ? ?  ? */
    if (XSOCKET_DEBUG) {
        xsocket_log.setLevel(Level.ALL);
    } else {
        xsocket_log.setLevel(Level.INFO);
    }
    ConsoleHandler console = new ConsoleHandler();
    if (XSOCKET_DEBUG) {
        console.setLevel(Level.ALL);
    } else {
        console.setLevel(Level.INFO);
    }
    xsocket_log.addHandler(console);
    /* xsocket  - FINE ???     ?  ? ?  ? */

    initLogger();

    initFilter();

    initStorage();

    InetAddress ia = InetAddress.getByName(HOST);
    if (ia == null) {
        ia = InetAddress.getLocalHost();
    }

    /*  ?   ( ) - Receive Buffer Size  ? */
    Map<String, Object> options = new HashMap<String, Object>();

    // - 2014.04.29 - ?   - START - Multiplexing?   .
    // options.put(IConnection.SO_REUSEADDR, true);
    // options.put(IConnection.SO_LINGER, "5"); // ?  ??     (? ? ?  )
    // options.put(IConnection.SO_KEEPALIVE, true);
    // options.put(IConnection.TCP_NODELAY, true);
    // options.put(IConnection.SO_RCVBUF, XNDiscConfig.INIT_BUFFER_SIZE);
    // options.put(IConnection.SO_SNDBUF, XNDiscConfig.INIT_BUFFER_SIZE);
    // - 2014.04.29 - ?   - END - Multiplexing?   .

    /* SERVER? ?  ?  */

    /*  workerpool (?? ?  ? )?    ?. */
    /* ? ? workerpool? ? ?    workerpool ? ?. ? 100. */
    System.setProperty(XNDiscUtils.XSOCKET_WORKER_POOL_MIN_SIZE, SIZE_WORKER_POOL);
    /*  workerpool?    ?. ? 4 */
    System.setProperty(XNDiscUtils.XSOCKET_WORKER_POOL_MIN_SIZE, MIN_SIZE_WORKER_POOL);
    /* ? ? (NIO Selectors)? . ? 2 ?  ?. */
    System.setProperty(XNDiscUtils.XSOKET_DISPATCHER_INIT_COUNT, DISPATCHER_INIT_COUNT);
    /*  ?? ? ??   */
    /*  , ??  ?? ?. ? ??  . */
    System.setProperty(XNDiscUtils.XSOCKET_DISPATCHER_MAX_HANDLE, DISPATCHER_MAX_HANDLES);
    /* ?  ? ?    ?? ?? ? . ? false. */
    System.setProperty(XNDiscUtils.XSOCKET_SERVER_READ_BUFFER_USEDIRECT, READ_BUFFER_USEDIRECT);

    // - 2014.04.25 - ByteBuffer Direct   - START
    System.setProperty(XNDiscUtils.XSOCKET_CLIENT_READ_BUFFER_USEDIRECT, READ_BUFFER_USEDIRECT);
    System.setProperty(XNDiscUtils.XSOCKET_WRITE_BUFFER_USEDIRECT, READ_BUFFER_USEDIRECT);
    // - 2014.04.25 - ByteBuffer Direct   - END

    // - 2014.04.29 -    - START
    System.setProperty(XNDiscUtils.XSOCKET_SUPPRESS_SYNC_FLUSH_WARNING, "true");
    System.setProperty(XNDiscUtils.XSOCKET_SUPPRESS_REUSE_BUFFER_WARNING, "true"); // or FlushMode.SYNC (GET ? )
    System.setProperty(XNDiscUtils.XSOCKET_SUPPRESS_SYNC_FLUSH_COMPLETION_HANDLER_WARNING, "true");
    System.setProperty(XNDiscUtils.XSOCKET_DISPATCHER_BYPASSING_WRITE_ALLOWED, "true");
    // - 2014.04.29 -    - END

    /* (NIO SelectionKey)?  ? true ? ?? detach?. ?? ???  .  false. */
    System.setProperty(XNDiscUtils.XSOCKET_DISPATCHER_DETACH_HANDLE_ON_NO_OPS, DETACH_HANDLE_NO_OPERATION);
    /* ? ??  ? ??   ? ?   (1024 * 16) */
    Integer mapped_bytebuffer_maxsize = 1024
            * XNDiscConfig.getInt(XNDiscConfig.TRANSFER_MAPPED_BYTE_BUFFER_MAXSIZE, 16);
    System.setProperty(XNDiscUtils.XSOCKET_TRANFER_MAPPED_BYTEBUFFER_MAX_SIZE,
            mapped_bytebuffer_maxsize.toString());

    /* ? Sever  - SSL ?   ?    Connection? ?  ?! */
    if (USE_SSL) {
        this.server = new Server(ia, PORT, options,
                new MultiplexedProtocolAdapter(new XNDiscHandler(storage, logger)),
                XNDiscSSLContextFactory.getSSLContext(), true);
        // this.server = new Server(ia, PORT, options, new XNDiscHandler(storage, logger), XNDiscSSLContextFactory.getSSLContext(), true);
    } else {
        this.server = new Server(ia, PORT, options,
                new MultiplexedProtocolAdapter(new XNDiscHandler(storage, logger)), null, false);
        // this.server = new Server(ia, PORT, options, new XNDiscHandler(storage, logger), null, false);
    }

    /*  ThreadPool? ? , Cached ?   ? ??? ?  ? ?  ?. */
    /* SERVER? ?  ? (? Fixed) */
    /*   ?  :  ? ?  ?? Runtime.availableProcessors() ? ? ?? ???   */
    /* newFixedThreadPool ?  ?  ? corePoolSize, maximumPoolSize  .  ?  */
    /* newCachedThreadPool ?  corePoolSize = 0, maximumPoolSize  Integer.MAX_VALUE  .  ? 1 */

    if (WORKER_POOL_TYPE.equals("C")) {
        this.server.setWorkerpool(Executors.newCachedThreadPool(new XNDiscThreadFactory(true)));
    } else {
        if (XNDiscConfig.getBoolean(XNDiscConfig.MULTIPLICATION_THREAD_AVAILABLE_PROCESSORS)) {
            WORKER_THREAD_POOL = Runtime.getRuntime().availableProcessors() * WORKER_THREAD_POOL;
        }
        this.server
                .setWorkerpool(Executors.newFixedThreadPool(WORKER_THREAD_POOL, new XNDiscThreadFactory(true)));
    }
    this.server.setFlushmode(FlushMode.ASYNC);
}

From source file:org.ensembl.healthcheck.StandaloneTestRunner.java

public Logger getLogger() {
    if (logger == null) {
        logger = Logger.getLogger(StandaloneTestRunner.class.getCanonicalName());
        ConsoleHandler localConsoleHandler = new ConsoleHandler();
        localConsoleHandler.setFormatter(new Formatter() {
            DateFormat format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");

            @Override//w  w w  .j a va 2s. co m
            public String format(LogRecord record) {
                return String.format("%s %s %s : %s%n", format.format(new Date(record.getMillis())),
                        record.getSourceClassName(), record.getLevel().toString(), record.getMessage());
            }
        });
        if (options.isVerbose()) {
            localConsoleHandler.setLevel(Level.ALL);
            logger.setLevel(Level.ALL);
        } else {
            localConsoleHandler.setLevel(Level.INFO);
            logger.setLevel(Level.INFO);
        }
        logger.setUseParentHandlers(false);
        logger.addHandler(localConsoleHandler);
    }
    return logger;
}

From source file:eu.asterics.mw.services.AstericsErrorHandling.java

/**
 * This method creates the logger. Actually there are 4 types of loggers: 
 * "severe": logs fatal errors i.e. errors that prevent the ARE from functioning
 * "warning": logs errors other than fatal e.g. component errors
 * "info": logs informative messages/*from w  ww  .  ja v a 2 s.  c  om*/
 * "fine": logs debugging messages
 * 
 * Each logger by default also logs all messages with severity level higher than its own. 
 * E.g. the warning logger logs warning and severe messages, the info logger logs info, 
 * warning and severe messages etc. The same applies to the consoleHandler, i.e. by 
 * setting its level to info, the console will also print severe and warning messages 
 * along with info messages
 */
public Logger getLogger() {
    if (logger == null) {
        logger = Logger.getLogger("AstericsLogger");

        FileHandler warningFileHandler, severeFileHandler, infoFileHandler, fineFileHandler;
        ConsoleHandler consoleHandler;
        try {
            //cleanup before starting:
            logger.setUseParentHandlers(false);

            // remove and handlers that will be replaced
            Handler[] handlers = logger.getHandlers();
            for (Handler handler : handlers) {
                if (handler.getClass() == ConsoleHandler.class)
                    logger.removeHandler(handler);
            }

            File logFolder = new File(System.getProperty(LOG_PATH_PROPERTY, ResourceRegistry.TMP_FOLDER));
            if (!logFolder.exists()) {
                FileUtils.forceMkdir(logFolder);
            }
            //Create handlers
            severeFileHandler = new FileHandler(new File(logFolder, "asterics_logger_severe.log").getPath(),
                    true);
            warningFileHandler = new FileHandler(new File(logFolder, "asterics_logger_warning.log").getPath(),
                    true);
            infoFileHandler = new FileHandler(new File(logFolder, "asterics_logger.log").getPath(), true);
            fineFileHandler = new FileHandler(new File(logFolder, "asterics_logger_fine.log").getPath(), true);
            consoleHandler = new ConsoleHandler();

            //Set report level of handlers
            severeFileHandler.setLevel(Level.SEVERE);
            warningFileHandler.setLevel(Level.WARNING);
            infoFileHandler.setLevel(Level.INFO);
            fineFileHandler.setLevel(Level.FINE);

            //The consoleHandler prints log messaged to the console. Its 
            //severety level can be adjusted accordingly. 
            String level = getLoggerLevel();
            switch (level) {
            case "INFO":
                consoleHandler.setLevel(Level.INFO);
                break;
            case "WARNING":
                consoleHandler.setLevel(Level.WARNING);
                break;
            case "FINE":
                consoleHandler.setLevel(Level.FINE);
                break;
            case "SEVERE":
                consoleHandler.setLevel(Level.SEVERE);
                break;

            default:
                consoleHandler.setLevel(Level.INFO);
                break;
            }

            //Add handlers to the logger
            logger.addHandler(warningFileHandler);
            logger.addHandler(severeFileHandler);
            logger.addHandler(infoFileHandler);
            logger.addHandler(fineFileHandler);
            logger.addHandler(consoleHandler);

            //Create formatters for the handlers (optional)
            severeFileHandler.setFormatter(new SimpleFormatter());
            warningFileHandler.setFormatter(new SimpleFormatter());
            infoFileHandler.setFormatter(new SimpleFormatter());
            fineFileHandler.setFormatter(new SimpleFormatter());
            consoleHandler.setFormatter(new SimpleFormatter());

            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);

        } catch (SecurityException e) {
            System.out.println(AstericsErrorHandling.class.getName() + ": Error creating AstericsLogger: "
                    + e.getMessage());
        } catch (IOException e) {
            //logger.warning(this.getClass().getName()+
            //   ": Error creating AstericsLogger: "+e.getMessage());
            System.out.println(AstericsErrorHandling.class.getName() + ": Error creating AstericsLogger: "
                    + e.getMessage());
        }
    }

    return logger;
}