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, boolean append) throws IOException, SecurityException 

Source Link

Document

Initialize a FileHandler to write to the given filename, with optional append.

Usage

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

/**
 * Executes the specified patch bundle./* www . j av  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.valygard.aohruthless.Joystick.java

/**
 * Not satisfied with global logging, which can become cluttered and messy
 * with many plugins or players using commands, etc, the Bukkit logger will
 * log all relevant information to a log file. This log file can be found in
 * the plugin data folder, in the subdirectory <i>logs</i>.
 * <p>//  w w w.ja  v  a 2  s.  c o m
 * The log file, <i>joystick.log</i>, will not be overriden. The logger will
 * simply append new information if the file already exists. All messages
 * will be logged in the format:<br>
 * [month-day-year hr-min-sec] (level): (message), where level is the
 * {@link LogRecord#getLevel()} and the message is the
 * {@link LogRecord#getMessage()}.
 * </p>
 * 
 * @return the created FileHandler, null if a SecurityException or
 *         IOException were thrown and handled.
 */
private FileHandler setupLogger() {
    File dir = new File(getDataFolder() + File.separator + "logs");
    dir.mkdirs();
    try {
        FileHandler handler = new FileHandler(dir + File.separator + "joystick.log", true);
        getLogger().addHandler(handler);
        handler.setFormatter(new SimpleFormatter() {

            @Override
            public String format(LogRecord record) {
                Date date = new Date();
                SimpleDateFormat df = new SimpleDateFormat("[MM-dd-yyyy HH:mm:ss]");
                return df.format(date) + " " + record.getLevel() + ":"
                // org.apache.commons.lang
                        + StringUtils.replace(record.getMessage(), "[Joystick]", "")
                        + System.getProperty("line.separator");
            }
        });
        return handler;
    } catch (SecurityException | IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/admineditscheduleblocks", method = RequestMethod.POST)
public String editScheduleBlocks(Model model, @RequestParam(value = "schoolID") String schoolID) {
    try {/*ww  w . j  a v a  2 s  . c  om*/
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBAdminScheduleBlocks.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        logger.info("Admin Viewing List of School's Schedule Blocks.");
        int schoolID2 = Integer.parseInt(schoolID);
        Schools school = SchoolDAO.getSchool(schoolID2);
        List<Scheduleblocks> sbs = ScheduleBlockDAO.getSchoolsScheduleBlocks(schoolID2);
        model.addAttribute("school", school);
        model.addAttribute("scheduleblocks", sbs);
        logger.info("School's schedule blocks successfully updated to model.");
        handler.close();
        logger.removeHandler(handler);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "admineditscheduleblocks";

}

From source file:com.basp.trabajo_al_minuto.model.business.BusinessUtils.java

public static void writeLog(String file, List<LogRecord> records) throws BusinessException {
    try {//from   w ww  .j a  v  a 2s .c o m
        Logger logger = Logger.getAnonymousLogger();
        SimpleFormatter formatter = new SimpleFormatter();
        FileHandler fh = new FileHandler(file, Boolean.TRUE);
        fh.setFormatter(formatter);
        logger.addHandler(fh);
        logger.setUseParentHandlers(false);
        records.stream().forEach((logRecord) -> {
            logger.log(logRecord);
        });
    } catch (IOException | SecurityException ex) {
        Logger.getLogger(BusinessUtils.class.getName()).log(Level.SEVERE, "BusinessUtils.writeLog Exception",
                ex);
        throw new BusinessException(ex);
    }
}

From source file:org.archive.crawler.framework.CrawlJob.java

/**
 * Get a logger to a distinguished file, job.log in the job's
 * directory, into which job-specific events may be reported.
 * //from   ww  w .  j a  v  a  2  s. co m
 * @return Logger writing to the job-specific log
 */
public Logger getJobLogger() {
    if (jobLogger == null) {
        jobLogger = Logger.getLogger(getShortName());
        try {
            mainJobLogHandler = new FileHandler(getJobLog().getAbsolutePath(), true);
            mainJobLogHandler.setFormatter(new JobLogFormatter());
            jobLogger.addHandler(mainJobLogHandler);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        jobLogger.setLevel(Level.INFO);
    }
    return jobLogger;
}

From source file:au.com.addstar.truehardcore.TrueHardcore.java

@Override
public void onEnable() {
    instance = this;

    // This block configure the logger with handler and formatter  
    try {//from w  ww.  j a va 2  s  .c o  m
        debuglog.setUseParentHandlers(false);
        debugfh = new FileHandler("plugins/TrueHardcore/debug.log", true);
        Util.LogFormatter formatter = new Util.LogFormatter();
        debugfh.setFormatter(formatter);
        debuglog.addHandler(debugfh);
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Grab that plugin manager!
    pdfFile = this.getDescription();
    pm = this.getServer().getPluginManager();

    // Check if vault is loaded (required for economy)
    VaultEnabled = setupEconomy();
    if (VaultEnabled) {
        Log("Found Vault! Hooking for economy!");
    } else {
        Log("Vault was not detected! Economy rewards are not available.");
    }

    Plugin p = pm.getPlugin("LWC");
    if (p != null && p instanceof LWCPlugin) {
        LWCHooked = true;
        lwc = ((LWCPlugin) p).getLWC();
        Log("LWC Found, hooking into LWC.");
    } else {
        LWCHooked = false;
        Log("LWC not Found");
    }

    p = pm.getPlugin("Prism");
    if (p != null && p instanceof Prism) {
        LBHooked = true;
        prism = (Prism) p;
        Log("Prism found, hooking it.");
    } else {
        LBHooked = false;
        Log("Prism not found! This won't work very well...");
    }

    p = pm.getPlugin("WorldBorder");
    if (p != null && p instanceof WorldBorder) {
        WBHooked = true;
        wb = WorldBorder.plugin;
        Log("WorldBorder found, hooking it.");
    } else {
        WBHooked = false;
        Log("WorldBorder not found! Spawning will not be limited...");
    }

    p = pm.getPlugin("BungeeChatBukkit");
    if (p != null && p instanceof BungeeChat) {
        BCHooked = true;
        Log("BungeeChat found, hooking it.");
    } else {
        BCHooked = false;
        Log("BungeeChat not found! No cross server messages");
    }

    p = pm.getPlugin("VanishNoPacket");
    if (p != null && p instanceof VanishPlugin) {
        VNPHooked = true;
        vnp = ((VanishPlugin) p).getManager();
        Log("VanishNoPacket found, hooking it.");
    } else {
        WBHooked = false;
        Log("VanishNoPacket not found! Vanished players will not be unvanished...");
    }

    // Read (or initialise) plugin config file
    cfg.LoadConfig(getConfig());

    // Save the default config (if one doesn't exist)
    saveDefaultConfig();

    // Open/initialise the database
    dbcon = new Database(this);
    if (dbcon.IsConnected) {
        Log("Successfully connected to the database.");
        Log("Loading players from database...");
        LoadAllPlayers();
    } else {
        Log(pdfFile.getName() + " " + pdfFile.getVersion() + " could not be enabled!");
        this.setEnabled(false);
        return;
    }

    Log("Registering commands and events...");
    getCommand("truehardcore").setExecutor(new CommandTH(this));
    getCommand("th").setExecutor(new CommandTH(this));

    pm.registerEvents(new PlayerListener(this), this);

    // Set auto save timer
    if (AutoSaveEnabled) {
        Log("Launching auto-save timer (every 5 minutes)...");
        getServer().getScheduler().runTaskTimer(this, new Runnable() {
            @Override
            public void run() {
                SaveIngamePlayers();
            }
        }, 300 * 20L, 300 * 20L);
    }

    Log(pdfFile.getName() + " " + pdfFile.getVersion() + " has been enabled");
}

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/addscheduleblock", method = RequestMethod.POST)
public String addScheduleBlock(Model model, @RequestParam(value = "schoolid") String schoolID,
        @RequestParam(value = "period") String period, @RequestParam(value = "days") String[] days) {
    try {/*w w w.  j ava 2  s  . c  om*/
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBAdminScheduleBlocks.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        logger.info("Admin Viewing List of School's Schedule Blocks.");
        int schoolID2 = Integer.parseInt(schoolID);
        if (period.isEmpty() || days.length == 0) {
            model.addAttribute("sbempty", "A field is empty");
        }
        int periodInt = Integer.parseInt(period);
        String daysString = "";
        for (String x : days) {
            daysString += x;
            daysString += ",";
        }
        daysString = daysString.substring(0, daysString.length() - 1);
        Scheduleblocks sb = ScheduleBlockDAO.getScheduleBlock(schoolID2, periodInt, daysString);
        if (sb != null) {
            model.addAttribute("sbexists", "This scheduleblock exists");
            logger.info("Error: SB exists");
        } else {
            ScheduleBlockDAO.addScheduleBlock(schoolID2, periodInt, daysString);
            logger.info(
                    "Scheduleblock with period " + periodInt + " and days " + daysString + " added to school.");
        }
        handler.close();
        logger.removeHandler(handler);
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return editScheduleBlocks(model, schoolID);
}

From source file:org.oscarehr.hospitalReportManager.SFTPConnector.java

/**
 * Main constructor. To change keys, manually set the references below.
 * //from   ww w .j av  a  2 s .c  o m
 * @param host
 * @param port
 * @param user
 * @param keyLocation
 * @throws Exception
 */
public SFTPConnector(String host, int port, String user, String keyLocation) throws Exception {

    logger.debug("Host " + host + " port " + port + " user " + user + " keyLocation " + keyLocation);

    //daily log file name follows "day month year . log" (with no spaces)
    String logName = SFTPConnector.getDayMonthYearTimestamp() + ".log";
    String fullLogPath = this.logDirectory + logName;

    //prepare the logger
    FileHandler handler = new FileHandler(fullLogPath, true); //append log to daily log files
    fLogger = Logger.getLogger("SFTPConnector");
    fLogger.addHandler(handler);

    jsch = new JSch();

    jsch.addIdentity(keyLocation);
    sess = jsch.getSession(user, host, port);

    java.util.Properties confProp = new java.util.Properties();
    confProp.put("StrictHostKeyChecking", "no");
    sess.setConfig(confProp);

    sess.connect();

    Channel channel = sess.openChannel("sftp");
    channel.connect();
    cmd = (ChannelSftp) channel;
    fLogger.info("SFTP connection established with " + host + ":" + port + ". Current path on server is: "
            + cmd.pwd());
}

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

/**
 * ???????./*w w  w  . j av  a2s  .  c om*/
 * @return ????????
 */
@Nonnull
private FileHandler createLogFileHandler() {
    try {
        FileHandler fh = new FileHandler(DefaultValues.USER_LOG_FILE.getAbsolutePathString(), true);
        //logger??JSON??
        fh.setFormatter(new OliviaLogFileFormatter());
        return fh;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

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 {/* www .  j a va  2  s  .  c o  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);

    //
    //
    //
}