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:com.redhat.rcm.version.Cli.java

private static void configureLogging(boolean useConsole, final boolean useLogFile, final File logFile) {
    System.out.println("Log file is: " + logFile.getAbsolutePath());

    final List<Handler> handlers = new ArrayList<Handler>();

    if (!useConsole && !useLogFile) {
        if (!useLogFile) {
            System.out.println(// ww w.j  av  a  2 s.co m
                    "\n\nNOTE: --no-console option has been OVERRIDDEN since --no-log-file option was also provided.\nOutputting to console ONLY.\n");
            useConsole = true;
        }
    }

    if (useConsole) {
        final Handler chandler = new ConsoleHandler();
        chandler.setFormatter(new VManFormatter());
        chandler.setLevel(Level.ALL);
        handlers.add(chandler);
    }

    if (useLogFile) {
        try {
            final File dir = logFile.getParentFile();
            if (dir != null && !dir.isDirectory() && !dir.mkdirs()) {
                throw new RuntimeException(
                        "Failed to create parent directory for logfile: " + dir.getAbsolutePath());
            }
            final Handler fhandler = new FileHandler(logFile.getPath(), false);
            fhandler.setFormatter(new VManFormatter());
            fhandler.setLevel(Level.ALL);
            handlers.add(fhandler);
        } catch (final IOException e) {
            final StringWriter sw = new StringWriter();
            final PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            System.out.printf("ERROR: Failed to initialize log file: %s. Reason: %s\n\n%s\n\n", logFile,
                    e.getMessage(), sw.toString());

            throw new RuntimeException("Failed to initialize logfile.");
        }
    }

    root.setUseParentHandlers(false);
    final Handler[] currenthandlers = root.getHandlers();
    for (final Handler h : currenthandlers) {
        h.close();
        root.removeHandler(h);
    }
    for (final Handler h : handlers) {
        root.addHandler(h);
    }
}

From source file:gtu.youtube.JavaYoutubeDownloader.java

private void changeFormatter(Formatter formatter) {
    Handler[] handlers = rootlog.getHandlers();
    for (Handler handler : handlers) {
        handler.setFormatter(formatter);
    }/* ww w .  java  2s  .  com*/
}

From source file:com.kyne.webby.rtk.modules.WebbyRTKModule.java

public WebbyRTKModule(final ModuleMetadata moduleMetadata, final ModuleLoader moduleLoader,
        final ClassLoader classLoader) {
    super(moduleMetadata, moduleLoader, classLoader, ToolkitEvent.ON_TOOLKIT_START, ToolkitEvent.NULL_EVENT);

    //Fix formatting on logger (Based on MilkAdmin)
    final Logger rootlog = Logger.getLogger("");
    for (final Handler h : rootlog.getHandlers()) { //remove all handlers
        h.setFormatter(new WebbyFormatter());
    }//from  www .j ava2  s  . c o m
    LogHelper.initLogger("WebbyRTKModule", "Minecraft");
}

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  w  w.ja va2 s.  c o  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:org.hillview.utils.HillviewLogger.java

/**
 * Create a Hillview logger.//  w  ww.j a v  a 2  s .  c om
 * @param role      Who is doing the logging: web server, worker, test, etc.
 * @param filename  File where logs are to be written.  If null logs will be written to the
 *                  console.
 */
private HillviewLogger(String role, @Nullable String filename) {
    // Disable all default logging
    LogManager.getLogManager().reset();
    this.logger = Logger.getLogger("Hillview");
    this.machine = this.checkCommas(Utilities.getHostName());
    this.role = this.checkCommas(role);
    this.logger.setLevel(Level.INFO);

    Formatter form = new SimpleFormatter() {
        final String[] components = new String[5];
        final String newline = System.lineSeparator();
        private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");

        @Override
        public synchronized String format(LogRecord record) {
            this.components[0] = HillviewLogger.this.checkCommas(df.format(new Date(record.getMillis())));
            this.components[1] = HillviewLogger.this.role;
            this.components[2] = HillviewLogger.this.checkCommas(record.getLevel().toString());
            this.components[3] = HillviewLogger.this.machine;
            this.components[4] = record.getMessage();
            String result = String.join(",", components);
            return result + this.newline;
        }
    };

    Handler handler;
    if (filename != null) {
        try {
            handler = new FileHandler(filename);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        handler = new ConsoleHandler();
    }
    handler.setFormatter(form);
    logger.addHandler(handler);
    File currentDirectory = new File(new File(".").getAbsolutePath());
    this.info("Starting logger", "Working directory: {0}", currentDirectory);
}

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/deleteschool", method = RequestMethod.POST)
public String deleteSchool(Model model, @RequestParam(value = "schoolID") int schoolID) {
    SchoolDAO.deleteSchool(schoolID);//from  w  w w  .  jav a  2s  .c o m
    try {
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBAdminSchools.log");
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        logger.info("Admin Viewing List of Schools.");
        SchoolDAO schoolDAO = new SchoolDAO();
        ScheduleBlockDAO scheduleBlockDAO = new ScheduleBlockDAO();
        List<Schools> schools = schoolDAO.allSchools();
        logger.info("Returning list of schools..." + schools.size() + " schools found.");
        for (Schools school : schools) {
            List<Scheduleblocks> scheduleBlocks = scheduleBlockDAO
                    .getSchoolsScheduleBlocks(school.getSchoolid());
            String SB2Strings = "";
            for (Scheduleblocks sb : scheduleBlocks) {
                SB2Strings += sb.toString();
            }
            school.setScheduleblocks(SB2Strings);
        }
        model.addAttribute("school", schools);
        logger.info("Schools successfully added to model.");
        handler.close();
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "admin";
}

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/deletescheduleblock", method = RequestMethod.POST)
public String deleteScheduleBlocks(Model model, @RequestParam(value = "scheduleblockID") String scheduleblockID,
        @RequestParam(value = "schoolid") String schoolid) {
    try {/*w  w  w . jav  a2s . 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 sbid = Integer.parseInt(scheduleblockID);
        ScheduleBlockDAO.deleteScheduleBlock(sbid);
        logger.info("Scheduleblock " + sbid + " was deleted.");
        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:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/admineditscheduleblocks", method = RequestMethod.POST)
public String editScheduleBlocks(Model model, @RequestParam(value = "schoolID") String schoolID) {
    try {/* w  w 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:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(Model model) {
    try {//from   w w w .  j a  v a2s.  com
        Handler handler = new FileHandler("%tBSxSBAdminSchools.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        logger.info("Admin Viewing List of Schools.");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        Admins admin = AdminDAO.getAdmin(name);
        if (!admin.getLoggedin()) {
            AdminDAO.setLoggedIn(name);
        }
        SchoolDAO schoolDAO = new SchoolDAO();
        ScheduleBlockDAO scheduleBlockDAO = new ScheduleBlockDAO();
        List<Schools> schools = schoolDAO.allSchools();
        for (Schools school : schools) {
            List<Scheduleblocks> scheduleBlocks = scheduleBlockDAO
                    .getSchoolsScheduleBlocks(school.getSchoolid());
            String SB2Strings = "";
            for (Scheduleblocks sb : scheduleBlocks) {
                SB2Strings += sb.toString();
            }
            school.setScheduleblocks(SB2Strings);
        }
        model.addAttribute("school", schools);
        logger.info("Schools 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 "admin";
}

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.  jav a  2 s. co  m*/
        //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);
}