Example usage for java.util.logging Handler setFormatter

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

Introduction

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

Prototype

public synchronized void setFormatter(Formatter newFormatter) throws SecurityException 

Source Link

Document

Set a Formatter .

Usage

From source file:mop.MemoryLogger.java

/**
 * A simple file logger which outputs only the message.
 *
 * @param fileName//w ww . jav  a 2  s  .co  m
 *            path to the output file
 * @return the logger
 */
private static Logger getFileLogger(String fileName) {
    final Logger logger = Logger.getLogger(fileName);
    try {
        logger.setUseParentHandlers(false);
        Handler handler = new FileHandler(fileName, true);
        handler.setFormatter(new Formatter() {
            @Override
            public String format(LogRecord record) {
                return record.getMessage() + "\n";
            }
        });
        logger.addHandler(handler);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return logger;
}

From source file:org.freaknet.gtrends.client.GoogleTrendsClientFactory.java

private static void setLogLevel(CmdLineParser cmdLine) throws SecurityException, IllegalArgumentException {
    final Level level;
    if (cmdLine.getLogLevel() != null) {
        level = Level.parse(cmdLine.getLogLevel());
    } else {/*from  w  w w. j  a v  a 2 s  .c  om*/
        level = Level.parse(DEFAULT_LOGGING_LEVEL);
    }
    Logger log = LogManager.getLogManager().getLogger("");

    for (Handler h : log.getHandlers()) {
        log.removeHandler(h);
    }
    Handler handler = new ConsoleHandler();
    handler.setFormatter(new LogFormatter());
    handler.setLevel(level);
    log.setUseParentHandlers(false);

    Logger defaultLog = Logger.getLogger(GoogleConfigurator.getLoggerPrefix());
    defaultLog.addHandler(handler);
    defaultLog.setLevel(level);
    defaultLog.setFilter(new Filter() {
        @Override
        public boolean isLoggable(LogRecord record) {
            if (record.getSourceClassName().startsWith(GoogleConfigurator.getLoggerPrefix())) {
                return (record.getLevel().intValue() >= level.intValue());
            }
            return false;
        }
    });
}

From source file:jshm.logging.Log.java

public static void configTestLogging() {
    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(Level.ALL);
    consoleHandler.setFormatter(new OneLineFormatter());

    Logger cur = Logger.getLogger("");
    removeHandlers(cur);/*from   ww  w  .  ja v a 2  s  .co m*/
    //      cur.setLevel(Level.ALL);

    cur.addHandler(consoleHandler);

    cur = Logger.getLogger("jshm");
    cur.setLevel(Level.ALL);

    cur = Logger.getLogger("httpclient.wire.header");
    cur.setLevel(Level.ALL);

    //      cur = Logger.getLogger("org.hibernate");
    //      removeHandlers(cur);
    //      
    //      cur.setLevel(Level.INFO);
}

From source file:jshm.logging.Log.java

public static void reloadConfig() throws Exception {
    // all logging
    Handler consoleHandler = new ConsoleHandler();
    consoleHandler.setLevel(DEBUG ? Level.ALL : Level.WARNING);
    consoleHandler.setFormatter(new OneLineFormatter());

    Logger cur = Logger.getLogger("");
    removeHandlers(cur);//ww w  . ja va2 s .  c  o  m

    cur.addHandler(consoleHandler);

    // jshm logging
    Formatter fileFormatter = new FileFormatter();
    Handler jshmHandler = new FileHandler("data/logs/JSHManager.txt");
    jshmHandler.setLevel(Level.ALL);
    jshmHandler.setFormatter(fileFormatter);

    cur = Logger.getLogger("jshm");
    cur.addHandler(jshmHandler);
    cur.setLevel(DEBUG ? Level.ALL : Level.INFO);

    // hibernate logging
    Handler hibernateHandler = new FileHandler("data/logs/Hibernate.txt");
    hibernateHandler.setLevel(Level.ALL);
    hibernateHandler.setFormatter(fileFormatter);

    cur = Logger.getLogger("org.hibernate");
    removeHandlers(cur);

    cur.addHandler(hibernateHandler);
    cur.setLevel(DEBUG ? Level.INFO : Level.WARNING);

    // HttpClient logging
    Handler httpClientHandler = new FileHandler("data/logs/HttpClient.txt");
    httpClientHandler.setLevel(Level.ALL);
    httpClientHandler.setFormatter(fileFormatter);

    //      cur = Logger.getLogger("httpclient.wire");
    cur = Logger.getLogger("httpclient.wire.header");
    removeHandlers(cur);

    cur.addHandler(httpClientHandler);
    cur.setLevel(DEBUG ? Level.ALL : Level.INFO);

    cur = Logger.getLogger("org.apache.commons.httpclient");
    removeHandlers(cur);

    cur.addHandler(httpClientHandler);
    cur.setLevel(DEBUG ? Level.FINER : Level.INFO);

    // HtmlParser logging
    Handler htmlParserHandler = new FileHandler("data/logs/HtmlParser.txt");
    htmlParserHandler.setLevel(Level.ALL);
    htmlParserHandler.setFormatter(fileFormatter);

    cur = Logger.getLogger("org.htmlparser");
    removeHandlers(cur);

    cur.addHandler(htmlParserHandler);
    cur.setLevel(DEBUG ? Level.ALL : Level.INFO);

    // SwingX logging
    Handler swingxHandler = new FileHandler("data/logs/SwingX.txt");
    swingxHandler.setLevel(Level.ALL);
    swingxHandler.setFormatter(fileFormatter);

    cur = Logger.getLogger("org.jdesktop.swingx");
    removeHandlers(cur);

    cur.addHandler(swingxHandler);
    cur.setLevel(DEBUG ? Level.ALL : Level.INFO);
}

From source file:org.forgerock.patch.Main.java

public static void execute(URL patchUrl, String originalUrlString, File workingDir, File installDir,
        Map<String, Object> params) throws IOException {

    try {/*from  w  ww  .  ja v  a  2  s. c  o m*/
        // Load the base patch configuration
        InputStream in = config.getClass().getResourceAsStream(CONFIG_PROPERTIES_FILE);
        if (in == null) {
            throw new PatchException(
                    "Unable to locate: " + CONFIG_PROPERTIES_FILE + " in: " + patchUrl.toString());
        } else {
            config.load(in);
        }

        // Configure logging and disable parent handlers
        SingleLineFormatter formatter = new SingleLineFormatter();
        Handler historyHandler = new FileHandler(workingDir + File.separator + PATCH_HISTORY_FILE, true);
        Handler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(formatter);
        historyHandler.setFormatter(formatter);
        history.setUseParentHandlers(false);
        history.addHandler(consoleHandler);
        history.addHandler(historyHandler);

        // Initialize the Archive
        Archive archive = Archive.getInstance();
        archive.initialize(installDir, new File(workingDir, PATCH_ARCHIVE_DIR),
                config.getString(PATCH_BACKUP_ARCHIVE));

        // Create the patch logger once we've got the archive directory
        Handler logHandler = new FileHandler(archive.getArchiveDirectory() + File.separator + PATCH_LOG_FILE,
                false);
        logHandler.setFormatter(formatter);
        logger.setUseParentHandlers(false);
        logger.addHandler(logHandler);

        // Instantiate the patcgh implementation and invoke the patch
        Patch patch = instantiatePatch();
        patch.initialize(patchUrl, originalUrlString, workingDir, installDir, params);
        history.log(Level.INFO, "Applying {0}, version={1}",
                new Object[] { config.getProperty(PATCH_DESCRIPTION), config.getProperty(PATCH_RELEASE) });
        history.log(Level.INFO, "Target: {0}, Source: {1}", new Object[] { installDir, patchUrl });
        patch.apply();

        history.log(Level.INFO, "Completed");
    } catch (PatchException pex) {
        history.log(Level.SEVERE, "Failed", pex);
    } catch (ConfigurationException ex) {
        history.log(Level.SEVERE, "Failed to load patch configuration", ex);
    } finally {
        try {
            Archive.getInstance().close();
        } catch (Exception ex) {
        }
        ;
    }
}

From source file:org.forgerock.openidm.patch.Main.java

/**
 * Executes the specified patch bundle./*www .  jav  a 2  s.c  o  m*/
 *
 * @param patchUrl          A URL specifying the location of the patch bundle
 * @param originalUrlString The String representation of the patch bundle location
 * @param workingDir        The working directory in which store logs and temporary files
 * @param installDir        The target directory against which the patch is to be applied
 * @param params            Additional patch specific parameters
 * @throws IOException      Thrown in the event of a failure creating the patch archive
 *                          or log files
 */
public static void execute(URL patchUrl, String originalUrlString, File workingDir, File installDir,
        Map<String, Object> params) throws IOException {

    try {
        // Load the base patch configuration
        InputStream in = CONFIG.getClass().getResourceAsStream(CONFIG_PROPERTIES_FILE);
        if (in == null) {
            throw new PatchException(
                    "Unable to locate: " + CONFIG_PROPERTIES_FILE + " in: " + patchUrl.toString());
        } else {
            CONFIG.load(in);
        }

        // Configure logging and disable parent handlers
        SingleLineFormatter formatter = new SingleLineFormatter();
        Handler historyHandler = new FileHandler(workingDir + File.separator + PATCH_HISTORY_FILE, true);
        Handler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(formatter);
        historyHandler.setFormatter(formatter);
        historyLogger.setUseParentHandlers(false);
        historyLogger.addHandler(consoleHandler);
        historyLogger.addHandler(historyHandler);

        // Initialize the Archive
        Archive archive = Archive.getInstance();
        archive.initialize(installDir, new File(workingDir, PATCH_ARCHIVE_DIR),
                CONFIG.getString(PATCH_BACKUP_ARCHIVE));

        // Create the patch logger once we've got the archive directory
        Handler logHandler = new FileHandler(archive.getArchiveDirectory() + File.separator + PATCH_LOG_FILE,
                false);
        logHandler.setFormatter(formatter);
        logger.setUseParentHandlers(false);
        logger.addHandler(logHandler);

        // Instantiate the patcgh implementation and invoke the patch
        Patch patch = instantiatePatch();
        patch.initialize(patchUrl, originalUrlString, workingDir, installDir, params);
        historyLogger.log(Level.INFO, "Applying {0}, version={1}",
                new Object[] { CONFIG.getProperty(PATCH_DESCRIPTION), CONFIG.getProperty(PATCH_RELEASE) });
        historyLogger.log(Level.INFO, "Target: {0}, Source: {1}", new Object[] { installDir, patchUrl });
        patch.apply();

        historyLogger.log(Level.INFO, "Completed");
    } catch (PatchException pex) {
        historyLogger.log(Level.SEVERE, "Failed", pex);
    } catch (ConfigurationException ex) {
        historyLogger.log(Level.SEVERE, "Failed to load patch configuration", ex);
    } finally {
        try {
            Archive.getInstance().close();
        } catch (IOException ex) {
            historyLogger.log(Level.SEVERE, "Failed to close patch archive", ex);
        }
    }
}

From source file:com.tri_voltage.md.io.YoutubeVideoParser.java

private static void changeFormatter(Formatter formatter) {
    Handler[] handlers = rootlog.getHandlers();
    for (Handler handler : handlers) {
        handler.setFormatter(formatter);
    }// w  w w  . ja v  a  2  s  .co m
}

From source file:fr.ens.transcriptome.teolenn.Main.java

/**
 * Parse the options of the command line
 * @param args command line arguments//from  w  w  w.  ja v  a  2  s. com
 * @return the number of optional arguments
 */
private static int parseCommandLine(final String args[]) {

    final Options options = makeOptions();
    final CommandLineParser parser = new GnuParser();

    int argsOptions = 0;

    try {

        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help"))
            help(options);

        if (line.hasOption("about"))
            about();

        if (line.hasOption("version"))
            version();

        if (line.hasOption("license"))
            license();

        // Load configuration if exists
        try {
            if (line.hasOption("conf")) {
                Settings.loadSettings(new File(line.getOptionValue("conf")));
                argsOptions += 2;
            } else
                Settings.loadSettings();
        } catch (IOException e) {
            logger.severe("Error while reading configuration file.");
            System.exit(1);
        }

        // Set the number of threads
        if (line.hasOption("threads"))
            try {
                argsOptions += 2;
                Settings.setMaxthreads(Integer.parseInt(line.getOptionValue("threads")));
            } catch (NumberFormatException e) {
                logger.warning("Invalid threads number");
            }

        // Set the verbose mode for extenal tools
        if (line.hasOption("verbose")) {
            Settings.setStandardOutputForExecutable(true);
            argsOptions++;
        }

        // Set Log file
        if (line.hasOption("log")) {

            argsOptions += 2;
            try {
                Handler fh = new FileHandler(line.getOptionValue("log"));
                fh.setFormatter(Globals.LOG_FORMATTER);
                logger.setUseParentHandlers(false);

                logger.addHandler(fh);
            } catch (IOException e) {
                logger.severe("Error while creating log file: " + e.getMessage());
                System.exit(1);
            }
        }

        // Set the silent option
        if (line.hasOption("silent"))
            logger.setUseParentHandlers(false);

        // Set log level
        if (line.hasOption("loglevel")) {

            argsOptions += 2;
            try {
                logger.setLevel(Level.parse(line.getOptionValue("loglevel").toUpperCase()));
            } catch (IllegalArgumentException e) {

                logger.warning("Unknown log level (" + line.getOptionValue("loglevel")
                        + "). Accepted values are [SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST].");

            }
        }

    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    } catch (SecurityException e) {
        logger.severe(e.getMessage());
        System.exit(1);
    }

    // If there is no arguments after the option, show help
    if (argsOptions == args.length) {
        System.err.println("No inputs files.");
        System.err.println("type: " + Globals.APP_NAME_LOWER_CASE + " -h for more informations.");
        System.exit(1);
    }

    return argsOptions;
}

From source file:net.oneandone.sushi.fs.webdav.WebdavFilesystem.java

public static void wireLog(String file) {
    Handler handler;

    WIRE.setLevel(Level.FINE);//  ww  w. ja  v  a  2s . c  o m
    try {
        handler = new FileHandler(file, false);
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    handler.setFormatter(new Formatter() {
        @Override
        public String format(LogRecord record) {
            String message;
            Throwable e;
            StringBuilder result;

            message = record.getMessage();
            result = new StringBuilder(message.length() + 1);
            result.append(message);
            result.append('\n');
            e = record.getThrown();
            if (e != null) {
                // TODO getStacktrace(e, result);
            }
            return result.toString();
        }
    });

    WIRE.addHandler(handler);
}

From source file:eu.abc4trust.abce.pertubationtests.tud.section2.PA_II_2_2_1malformedCEuri.java

@BeforeClass
public static void setupLogger() throws SecurityException, IOException {
    Handler fh = new FileHandler("PA-Section-2.2.1-malformedCE.log");
    SimpleFormatter simpleFormatter = new SimpleFormatter();
    fh.setFormatter(simpleFormatter);
    logger.addHandler(fh);//  ww  w  .j  av a  2 s  .  c o m
}