Example usage for java.util.logging FileHandler setFormatter

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

Introduction

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

Prototype

public synchronized void setFormatter(Formatter newFormatter) throws SecurityException 

Source Link

Document

Set a Formatter .

Usage

From source file:org.ejbca.ui.tcp.CmpTcpServer.java

public void start() throws UnknownHostException {
    final String cmdHandle = org.ejbca.ui.tcp.CmpTcpCommandHandler.class.getName();

    myServer = new QuickServer();
    myServer.setClientAuthenticationHandler(null);
    myServer.setBindAddr(CmpTcpConfiguration.getTCPBindAdress());
    myServer.setPort(CmpTcpConfiguration.getTCPPortNumber());
    myServer.setName("CMP TCP Server v " + VER);
    if (QuickServer.getVersionNo() >= 1.2) {
        LOG.info("Using 1.2 feature");
        myServer.setClientBinaryHandler(cmdHandle);
        myServer.setClientEventHandler(cmdHandle);

        //reduce info to Console
        myServer.setConsoleLoggingToMicro();
    }/*from  w w  w . j a  v a  2s  . c om*/

    //setup logger to log to file
    Logger logger = null;
    FileHandler txtLog = null;
    final String logDir = CmpTcpConfiguration.getTCPLogDir();
    final File logFile = new File(logDir + "/");
    if (!logFile.canRead()) {
        logFile.mkdir();
    }
    try {
        logger = Logger.getLogger("");
        logger.setLevel(Level.INFO);

        logger = Logger.getLogger("cmptcpserver");
        logger.setLevel(Level.FINEST);
        txtLog = new FileHandler(logDir + "/cmptcpserver.log");
        //reduce info 
        txtLog.setFormatter(new org.quickserver.util.logging.MicroFormatter());
        logger.addHandler(txtLog);

        myServer.setAppLogger(logger); //imp

        //myServer.setConsoleLoggingToMicro();
        myServer.setConsoleLoggingFormatter("org.quickserver.util.logging.SimpleTextFormatter");
        myServer.setConsoleLoggingLevel(Level.INFO);
    } catch (Exception e) {
        LOG.error("Could not create xmlLog FileHandler : ", e);
    }
    try {
        final String confFile = CmpTcpConfiguration.getTCPConfigFile();
        if (!StringUtils.isEmpty(confFile)) {
            final Object config[] = new Object[] { confFile };
            if (!myServer.initService(config)) {
                LOG.error("Configuration from config file " + confFile + " failed!");
            }
        }
        myServer.startServer();
        //myServer.getQSAdminServer().setShellEnable(true);
        //myServer.startQSAdminServer();         
    } catch (AppException e) {
        LOG.error("Error in server : ", e);
    }
}

From source file:com.nilostep.xlsql.database.xlInstanceOLD.java

private xlInstanceOLD(String cfg) throws xlException {
    logger = Logger.getLogger(this.getClass().getName());
    instance = this;
    //name = cfg;

    try {/*  ww w.j av a 2s.co m*/
        //            file = new File(cfg + "_config.xml");
        //            handler = new XMLFileHandler();
        //            handler.setFile(file);
        //
        //            cm = ConfigurationManager.getInstance();
        //            config = cm.getConfiguration(name);
        //            config.addConfigurationListener(this);
        //
        //            if (file.exists()) {

        PropertiesConfiguration config = new PropertiesConfiguration();
        config.load(this.getClass().getResourceAsStream(cfg + ".properties"));
        String engine = config.getString("general.engine");

        //cm.load(handler, name);                
        //Category cat = config.getCategory("general");                                                                
        //engine = config.getProperty("engine", null, "general");
        //config.setCategory(engine, true);
        //logger.info("Configuration file: " + file + " loaded");
        logger.info("Configuration engine: " + engine + " loaded");
        //            } else {

        //
        //                assert (config.isNew());
        //
        //                //
        //                config.setCategory("general", true);
        //
        //                String engine = "hsqldb";
        //                setLog("xlsql.log");
        //                setDatabase(System.getProperty("user.dir"));
        //
        //                //
        //                this.engine = engine;
        //                this.config.setProperty("engine", engine);
        //                addEngine(engine);
        //                config.setCategory(engine, true);
        //
        //
        //                //
        //                setDriver("org.hsqldb.jdbcDriver");
        //                setUrl("jdbc:hsqldb:.");
        //                setSchema("");
        //                setUser("sa");
        //                setPassword("");
        //                config.setCategory(getEngine(), true);
        //                logger.info("Configuration file: " + file + " created.");
        //            }
    }
    //catch (ConfigurationManagerException cme) {
    //   config = cm.getConfiguration(name);
    //} 
    catch (ConfigurationException e) {
        e.printStackTrace();
        throw new xlException(e.getMessage());
    }

    try {
        if (getLog() == null) {
            setLog("xlsql.log");
        }

        boolean append = true;
        FileHandler loghandler = new FileHandler(getLog(), append);
        loghandler.setFormatter(new SimpleFormatter());
        logger.addHandler(loghandler);
    } catch (IOException e) {
        throw new xlException("error while creating logfile");
    }

    //logger.info("Instance created with engine " + getEngine());
    logger.info("Instance created with engine " + engine);

    //
    //
    //
}

From source file:de.teamgrit.grit.entities.Controller.java

/**
 * Instantiates a new controller.//from www  . j av  a  2 s .  com
 */
private Controller() {
    m_courses = new HashMap<>();
    m_connections = new HashMap<>();

    try {
        // create log directory if it does not exist
        if (!Paths.get("log").toFile().exists()) {
            File logFolder = new File("log");
            logFolder.mkdir();
        }
        // Tell the logger to log there.
        FileHandler fh = new FileHandler(Paths.get("log", "system.log").toString(), true);
        LOGGER.addHandler(fh);

        // log in human readable format
        fh.setFormatter(new SimpleFormatter());

        // do not log to console
        LOGGER.setUseParentHandlers(false);
    } catch (SecurityException | IOException e) {
        System.err.println("Could not start logger on log/system.log: " + e.getMessage());
        e.printStackTrace();
    }
    try {
        m_config = new Configuration(CONFIG_LOCATION.toFile());
    } catch (ConfigurationException | FileNotFoundException e) {
        LOGGER.severe("Error while creating Controller: " + e.getMessage());
    }
}

From source file:org.apache.directory.studio.connection.core.io.jndi.LdifSearchLogger.java

/**
 * Inits the search logger./*from  ww w.  j  a v a2 s  .  c  om*/
 */
private void initSearchLogger(Connection connection) {
    Logger logger = Logger.getAnonymousLogger();
    loggers.put(connection.getId(), logger);
    logger.setLevel(Level.ALL);

    String logfileName = ConnectionManager.getSearchLogFileName(connection);
    try {
        FileHandler fileHandler = new FileHandler(logfileName, getFileSizeInKb() * 1000, getFileCount(), true);
        fileHandlers.put(connection.getId(), fileHandler);
        fileHandler.setFormatter(new Formatter() {
            public String format(LogRecord record) {
                return record.getMessage();
            }
        });
        logger.addHandler(fileHandler);
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.yahoo.dba.perf.myperf.common.MyPerfContext.java

private void configureLogging() {
    Logger logger = Logger.getLogger("");
    try {/*w  w  w .  j  a v a2s.  co m*/
        logger.setLevel(Level.parse(getLogLevel()));
    } catch (Exception ex) {
        logger.setLevel(Level.INFO);
    }
    try {
        for (Handler h : logger.getHandlers()) {
            if (h instanceof java.util.logging.ConsoleHandler)
                h.setLevel(Level.SEVERE);
        }
        String logRoot = System.getProperty("logPath", ".");

        java.util.logging.FileHandler fileHandler = new java.util.logging.FileHandler(
                logRoot + File.separatorChar + getLogPath(), this.logFileSize, this.logFileCount);
        fileHandler.setLevel(logger.getLevel());
        fileHandler.setFormatter(new SimpleFormatter());
        logger.addHandler(fileHandler);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandler.java

/**
 * Creates a new logger/*from   w  ww.  j a  v a  2 s.co  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:org.openconcerto.sql.PropsConfiguration.java

public void setupLogging(final String dirName, final boolean redirectToFile) {
    final File logDir;
    synchronized (this.restLock) {
        if (this.logDir != null)
            throw new IllegalStateException("Already set to " + this.logDir);
        logDir = getValidLogDir(dirName);
        this.logDir = logDir;
    }/*  w  w w. j a  v a 2s  .co m*/
    final String logNameBase = this.getAppName() + "_" + getLogDateFormat().format(new Date());

    // must be done before setUpConsoleHandler(), otherwise log output not redirected
    if (redirectToFile) {
        final File logFile = new File(logDir, (logNameBase + ".txt"));
        try {
            FileUtils.mkdir_p(logFile.getParentFile());
            System.out.println("Log file: " + logFile.getAbsolutePath());
            final OutputStream fileOut = new FileOutputStream(logFile, true);
            final OutputStream out, err;
            System.out.println("Java System console:" + System.console());
            boolean launchedFromEclipse = new File(".classpath").exists();
            if (launchedFromEclipse) {
                System.out.println("Launched from eclipse");
            }
            if ((System.console() != null || launchedFromEclipse)
                    && this.keepStandardStreamsWhenRedirectingToFile()) {
                System.out.println("Redirecting standard output to file and console");
                out = new MultipleOutputStream(fileOut, new FileOutputStream(FileDescriptor.out));
                System.out.println("Redirecting error output to file and console");
                err = new MultipleOutputStream(fileOut, new FileOutputStream(FileDescriptor.err));

            } else {
                out = fileOut;
                err = fileOut;
            }
            System.setErr(new PrintStream(new BufferedOutputStream(err, 128), true));
            System.setOut(new PrintStream(new BufferedOutputStream(out, 128), true));
            // Takes about 350ms so run it async
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        FileUtils.ln(logFile, new File(logDir, "last.log"));
                    } catch (final IOException e) {
                        // the link is not important
                        e.printStackTrace();
                    }
                }
            }).start();
        } catch (final Exception e) {
            ExceptionHandler.handle("Redirection des sorties standards impossible", e);
        }
    } else {
        System.out.println("Standard streams not redirected to file");
    }

    // removes default
    LogUtils.rmRootHandlers();
    // add console handler
    LogUtils.setUpConsoleHandler();
    // add file handler (supports concurrent launches, doesn't depend on date)
    try {
        final File logFile = new File(logDir, this.getAppName() + "-%u-age%g.log");
        FileUtils.mkdir_p(logFile.getParentFile());
        System.out.println("Logger logs: " + logFile.getAbsolutePath());
        // 2 files of at most 5M, each new launch append
        // if multiple concurrent launches %u is used
        final FileHandler fh = new FileHandler(logFile.getPath(), 5 * 1024 * 1024, 2, true);
        fh.setFormatter(new SimpleFormatter());
        Logger.getLogger("").addHandler(fh);
    } catch (final Exception e) {
        ExceptionHandler.handle("Enregistrement du Logger dsactiv", e);
    }

    this.setLoggersLevel();
}

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  w w .  j ava  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;
}

From source file:net.sf.dvstar.transmission.TransmissionView.java

private void initLogger() {

    try {/*from  www  .  j a  v  a  2  s . c o m*/
        FileHandler logFile = new FileHandler("%h/.JTransmission.log", true);
        logFile.setFormatter(new SimpleFormatter());

        globalLogger = Logger.getAnonymousLogger();
        Handler h[] = getGlobalLogger().getHandlers();
        for (int i = 0; i < h.length; i++) {
            globalLogger.removeHandler(h[i]);
        }

        globalLogger.addHandler(logFile);

        globalLogger.setLevel(logginLevel);
        globalLogger.setUseParentHandlers(false);

        globalLogger.log(Level.INFO, "Started");
        logFile.flush();
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

}