Example usage for java.util.logging FileHandler FileHandler

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:org.jamwiki.utils.WikiLogger.java

/**
 *
 *//*from   w  w  w.  ja  v  a 2 s.c o m*/
private static void initializeLogParams() {
    FileInputStream stream = null;
    try {
        File propertyFile = WikiLogger.loadProperties();
        stream = new FileInputStream(propertyFile);
        Properties properties = new Properties();
        properties.load(stream);
        String pattern = properties.getProperty("org.jamwiki.pattern");
        int limit = new Integer(properties.getProperty("org.jamwiki.limit")).intValue();
        int count = new Integer(properties.getProperty("org.jamwiki.count")).intValue();
        boolean append = Boolean.valueOf(properties.getProperty("org.jamwiki.append")).booleanValue();
        String datePattern = properties.getProperty("org.jamwiki.timestamp");
        DEFAULT_LOG_LEVEL = Level.parse(properties.getProperty("org.jamwiki.level"));
        WikiLogger.DEFAULT_LOG_HANDLER = new FileHandler(pattern, limit, count, append);
        DEFAULT_LOG_HANDLER.setFormatter(new WikiLogFormatter(datePattern));
        DEFAULT_LOG_HANDLER.setLevel(DEFAULT_LOG_LEVEL);
        // test the logger to verify permissions are OK
        Logger logger = Logger.getLogger(WikiLogger.class.getName());
        logger.addHandler(WikiLogger.DEFAULT_LOG_HANDLER);
        logger.setLevel(DEFAULT_LOG_LEVEL);
        logger.config("JAMWiki log initialized from " + propertyFile.getPath() + " with pattern " + pattern);
    } catch (Exception e) {
        System.out.println("WARNING: Unable to load custom JAMWiki logging configuration, using system default "
                + e.getMessage());
        WikiLogger.DEFAULT_LOG_HANDLER = null;
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.twitter.heron.common.utils.logging.LoggingHelper.java

/**
 * Initialize a <tt>FileHandler</tt> to write to a set of files
 * with optional append.  When (approximately) the given limit has
 * been written to one file, another file will be opened.  The
 * output will cycle through a set of count files.
 * The pattern of file name should be: ${processId}.log.index
 * <p>//from  ww w  .j  a v  a  2  s. c  o  m
 * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt>
 * properties (or their default values) except that the given pattern
 * argument is used as the filename pattern, the file limit is
 * set to the limit argument, and the file count is set to the
 * given count argument, and the append mode is set to the given
 * <tt>append</tt> argument.
 * <p>
 * The count must be at least 1.
 *
 * @param limit the maximum number of bytes to write to any one file
 * @param count the number of files to use
 * @param append specifies append mode
 * @throws IOException if there are IO problems opening the files.
 * @throws SecurityException if a security manager exists and if
 * the caller does not have <tt>LoggingPermission("control")</tt>.
 * @throws IllegalArgumentException if {@code limit < 0}, or {@code count < 1}.
 * @throws IllegalArgumentException if pattern is an empty string
 */
public static FileHandler getFileHandler(String processId, String loggingDir, boolean append, ByteAmount limit,
        int count) throws IOException, SecurityException {

    String pattern = loggingDir + "/" + processId + ".log.%g";

    FileHandler fileHandler = new FileHandler(pattern, (int) limit.asBytes(), count, append);
    fileHandler.setFormatter(new SimpleFormatter());
    fileHandler.setEncoding(StandardCharsets.UTF_8.toString());

    return fileHandler;
}

From source file:primarydatamanager.PrimaryDataManager.java

public static void main(String[] args) {
    // setup logging
    try {/*from  ww w. j a  va2 s  . co  m*/
        // Get the default Logger
        Logger mainLogger = Logger.getLogger("");
        mainLogger.setLevel(Level.FINEST);

        Handler consoleHandler = mainLogger.getHandlers()[0];
        consoleHandler.setLevel(Level.FINEST);
        consoleHandler.setFormatter(new VerySimpleFormatter());

        // Add a file handler
        new File("log").mkdir();
        Handler fileHandler = new FileHandler("log/datamanager.log", 50000, 2, true);
        fileHandler.setLevel(Level.INFO);
        mainLogger.addHandler(fileHandler);
    } catch (IOException exc) {
        System.out.println("Can't create log file");
        exc.printStackTrace();
    }

    // Start the update
    if (args.length == 0) {
        System.out.println("USAGE: PrimaryDataManager [-forceCompleteUpdate [channel{;channel}]] groups...");
        System.exit(1);
    } else {
        try {
            PrimaryDataManager manager = new PrimaryDataManager(new File("."));
            ArrayList<String> groupNames = new ArrayList<String>();
            for (int i = 0; i < args.length; i++) {
                if (args[i].equalsIgnoreCase("-forceCompleteUpdate")) {
                    if ((i + 1) >= args.length) {
                        System.out.println("You have to specify a colon separated "
                                + "list of channels after -forceCompleteUpdate");
                        System.exit(1);
                    } else {
                        i++;
                        StringTokenizer tokenizer = new StringTokenizer(args[i], ":");
                        while (tokenizer.hasMoreTokens()) {
                            manager.forceCompleteUpdateFor(tokenizer.nextToken());
                        }
                    }
                } else {
                    final String[] groups = args[i].split(",");
                    groupNames.addAll(Arrays.asList(groups));
                }
            }

            if (groupNames.size() == 0) {
                System.out.println("Please specify at least one channel group");
                System.exit(-1);
            }

            if (!manager.doesPreparedExist()) {
                System.out.println(
                        "The prepared directory is missing, this directory is very important and shouldn't "
                                + "be deleted, because this leeds to massiv problems.");
                System.exit(-1);
            }

            if (!manager.createLockFile()) {
                System.out.println("The PrimaryDataManager is already running.");
                System.exit(-1);
            }

            String[] groupNamesArr = new String[groupNames.size()];
            groupNames.toArray(groupNamesArr);
            manager.setGroupNames(groupNamesArr);

            manager.updateRawDataDir();

            manager.deleteLockFile();

            // Exit with error code 2 if some day programs were put into quarantine
            if (manager.mRawDataProcessor.getQuarantineCount() != 0) {
                System.exit(2);
            }
        } catch (PreparationException exc) {
            exc.printStackTrace();
            System.exit(1);
        }
    }
}

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

/**
 * Inits the search logger.//w  w  w .j  ava2s.  c o  m
 */
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:cz.cas.lib.proarc.desa.SIP2DESATransporter.java

private Handler setupLogHandler(String fileName) {
    Handler handler;//www. ja  v  a2s  .  c o m
    try {
        checkDirectory(logRoot);
        handler = new FileHandler(logRoot + System.getProperty("file.separator") + fileName + ".txt", 0, 1,
                true);
        handler.setFormatter(new SimpleFormatter());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Logger.getLogger("").addHandler(handler);

    return handler;
}

From source file:org.syncany.cli.CommandLineClient.java

private void initLogHandlers(OptionSet options, OptionSpec<String> optionLog, OptionSpec<Void> optionLogPrint,
        OptionSpec<Void> optionDebug) throws SecurityException, IOException {

    // --log=<file>
    String logFilePattern = null;

    if (options.has(optionLog)) {
        if (!"-".equals(options.valueOf(optionLog))) {
            logFilePattern = options.valueOf(optionLog);
        }//from w  w w .ja v a 2s .c o  m
    } else if (config != null && config.getLogDir().exists()) {
        logFilePattern = config.getLogDir() + File.separator + LOG_FILE_PATTERN;
    } else {
        logFilePattern = UserConfig.getUserLogDir() + File.separator + LOG_FILE_PATTERN;
    }

    if (logFilePattern != null) {
        Handler fileLogHandler = new FileHandler(logFilePattern, LOG_FILE_LIMIT, LOG_FILE_COUNT, true);
        fileLogHandler.setFormatter(new LogFormatter());

        Logging.addGlobalHandler(fileLogHandler);
    }

    // --debug, add console handler
    if (options.has(optionDebug) || options.has(optionLogPrint)
            || (options.has(optionLog) && "-".equals(options.valueOf(optionLog)))) {
        Handler consoleLogHandler = new ConsoleHandler();
        consoleLogHandler.setFormatter(new LogFormatter());

        Logging.addGlobalHandler(consoleLogHandler);
    }
}

From source file:org.kawanfw.commons.api.server.DefaultCommonsConfigurator.java

/**
 * @return a Logger whose pattern is located in
 *         <code>user.home/.kawansoft/log/kawanfw.log</code>, that uses a
 *         {@link SingleLineFormatter} and that logs 50Mb into 4 rotating
 *         files./*from  w ww  .  j  a va  2  s .  co  m*/
 */

@Override
public Logger getLogger() throws IOException {

    if (KAWANFW_LOGGER == null) {

        File logDir = new File(FrameworkFileUtil.getUserHomeDotKawansoftDir() + File.separator + "log");
        logDir.mkdirs();

        String logFilePattern = logDir.toString() + File.separator + "kawanfw.log";

        KAWANFW_LOGGER = Logger.getLogger("KawanfwLogger");
        int limit = 50 * 1024 * 1024;
        Handler fh = new FileHandler(logFilePattern, limit, 4, true);
        fh.setFormatter(new SingleLineFormatter(false));
        KAWANFW_LOGGER.addHandler(fh);
    }

    return KAWANFW_LOGGER;
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/** Creates a log handler for the stats logging.
 * @param newLogSet An identifier: "A" or "B".
 *///from ww w .  j  a  v a2 s.c om
private Handler makeLogHandler(String newLogSet) {
    Handler handler = null;
    try {
        String pattern = "VirtMus-" + newLogSet + "-%g.log";
        File logFile = getLogFile(pattern);
        handler = new FileHandler(logFile.getAbsolutePath(), 50 * 1000 * 1000, 10, true);
        handler.setFormatter(new XMLFormatter());
        handler.setEncoding("utf-8");
    } catch (IOException | SecurityException ex) {
        Log.log(ex);
    }
    return handler;
}

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

/**
 * Creates a new logger//from  w w w .  jav  a2 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: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  va 2  s.  c o  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();
}