Example usage for java.util.logging ConsoleHandler setFormatter

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

Introduction

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

Prototype

public synchronized void setFormatter(Formatter newFormatter) throws SecurityException 

Source Link

Document

Set a Formatter .

Usage

From source file:org.ocsoft.olivia.logger.LogStation.java

/**
 * ????./* w  ww. jav  a 2  s .com*/
 * @return ?????
 */
@Nonnull
private ConsoleHandler createConsoleLogHandler() {
    ConsoleHandler ch = new ConsoleHandler();
    //logger??JSON??
    ch.setFormatter(new OliviaConsoleLogFormatter());
    return ch;
}

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/*from w  w  w  .j a  v a 2  s  .c o 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:de.phillme.PhotoSorter.java

private void initLogging() {
    System.setProperty("java.util.logging.SimpleFormatter.format", "%5$s %n");
    LOGGER.setLevel(Level.INFO);//from   www. j  av  a 2 s .  co  m
    ConsoleHandler handler = new ConsoleHandler();
    handler.setFormatter(new SimpleFormatter());
    handler.setLevel(Level.INFO);
    LOGGER.addHandler(handler);
    LOGGER.setUseParentHandlers(false);
}

From source file:majordodo.task.BrokerTestUtils.java

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

        @Override//  ww  w.  j a  va2 s.  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:nl.strohalm.cyclos.utils.logging.LoggingHandler.java

/**
 * Creates a new logger//from   www. ja v a 2  s  .  c  o  m
 */
private Logger init(final Level level, final String file) {
    final LogSettings logSettings = settingsService.getLogSettings();
    final Logger logger = Logger.getAnonymousLogger();
    logger.setLevel(level);
    logger.setUseParentHandlers(false);
    try {
        final FileUnits units = logSettings.getMaxLengthPerFileUnits();
        final FileHandler fileHandler = new FileHandler(file,
                units.calculate(logSettings.getMaxLengthPerFile()), logSettings.getMaxFilesPerLog(), true);
        fileHandler.setFormatter(logFormatter);
        fileHandler.setEncoding(settingsService.getLocalSettings().getCharset());
        logger.addHandler(fileHandler);
    } catch (final Exception e) {
        final ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(logFormatter);
        try {
            consoleHandler.setEncoding(settingsService.getLocalSettings().getCharset());
        } catch (final Exception e1) {
            // Just ignore
        }
        logger.addHandler(consoleHandler);
        logger.log(Level.WARNING, "Unable to create logger for file " + file);
    }
    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//w ww. j  a  v a  2 s .  c o m
 * "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;
}