Example usage for java.util.logging SimpleFormatter SimpleFormatter

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

Introduction

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

Prototype

SimpleFormatter

Source Link

Usage

From source file:org.archive.crawler.reporting.CrawlerLoggerModule.java

private void setupAlertLog(String logsPath) throws IOException {
    Logger logger = Logger.getLogger(LOGNAME_ALERTS + "." + logsPath);
    String filename = getAlertsLogPath().getFile().getAbsolutePath();
    GenerationFileHandler fh = GenerationFileHandler.makeNew(filename, false, true);
    fh.setFormatter(new SimpleFormatter());
    AlertThreadGroup.current().addLogger(logger);
    AlertHandler.ensureStaticInitialization();
    logger.addHandler(fh);/*from   w  w w.ja  v  a  2  s .  co m*/
    addToManifest(filename, MANIFEST_LOG_FILE, true);
    logger.setUseParentHandlers(false);
    this.fileHandlers.put(logger, fh);
}

From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java

@Test(timeout = 120 * 60 * 1000L)
public void repeatTest() throws Throwable {
    DateFormat df = new SimpleDateFormat("_yyyy-MM-dd_hh-mm");
    int repeat = 1;
    for (int i = 1; i <= repeat; i++) {
        //overwrites any existing file with that name.
        String filePattern = "azuretest" + i + df.format(new Date()) + ".log";
        FileHandler fileHandler = new FileHandler(filePattern);
        fileHandler.setFormatter(new SimpleFormatter());
        logger.addHandler(fileHandler);// ww  w .  ja va 2s.c o m

        logger.info("Starting test iteration #" + i);
        boolean failed = false;
        try {
            before();
            test();
        } catch (Throwable t) {
            failed = true;
            throw t;
        } finally {
            if (failed) {
                logger.info(
                        "Failed test iteration #" + i + ". Machines are left running for manual diagnostics");
                logger.removeHandler(fileHandler);
                try {
                    SimpleMail.send("Azure test failed\nSubscription ID="
                            + credentials.getHostedServicesSubscriptionId(), new File(filePattern));
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "Failed to send email", e);
                }
                after();
                // no need to break since an exception was raised and is going to fail the test
            } else {
                logger.info("Passed test iteration #" + i);
                logger.removeHandler(fileHandler);
                try {
                    SimpleMail.send("Azure test passed\nSubscription ID="
                            + credentials.getHostedServicesSubscriptionId(), new File(filePattern));
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "Failed to send email", e);
                }
                after();
                // no need to break since we want to test the run multiple times (or until it fails)
            }
        }
    }
}

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);/*ww w  .jav a2s.  co  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:com.bc.fiduceo.post.PostProcessingToolTest.java

@Test
public void testThatPostProcessingToolInCaseOfExceptionsPrintsTheErrorMessageAndContinueWithTheNextFile()
        throws Exception {
    final ArrayList<Path> mmdFiles = new ArrayList<>();
    mmdFiles.add(Paths.get("nonExistingFileOne"));
    mmdFiles.add(Paths.get("nonExistingFileTwo"));
    mmdFiles.add(Paths.get("nonExistingFileThree"));

    final Formatter formatter = new SimpleFormatter();
    final ByteArrayOutputStream stream = new ByteArrayOutputStream();
    final StreamHandler handler = new StreamHandler(stream, formatter);
    final Logger logger = FiduceoLogger.getLogger();
    FiduceoLogger.setLevelSilent();//from   www . j  a v a  2 s . c  o m

    try {
        logger.addHandler(handler);

        final PostProcessingContext context = new PostProcessingContext();
        final PostProcessingConfig processingConfig = getConfig();
        context.setProcessingConfig(processingConfig);

        final PostProcessingTool postProcessingTool = new PostProcessingTool(context);

        postProcessingTool.computeFiles(mmdFiles);

        handler.close();
        final String string = stream.toString();
        assertThat(string, CoreMatchers.containsString("nonExistingFileOne"));
        assertThat(string, CoreMatchers.containsString("nonExistingFileTwo"));
        assertThat(string, CoreMatchers.containsString("nonExistingFileThree"));
    } finally {
        logger.removeHandler(handler);
    }
}

From source file:BSxSB.Controllers.StudentController.java

@RequestMapping(value = "/studenteditassigned", method = RequestMethod.GET)
public String editAssigned(Model model) {
    try {/*from w w  w.  j a  va 2s. c  o  m*/
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBStudentAssignedCourses.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        Students currentStudent = StudentDAO.getStudent(name);
        List<Courses> courses = CourseDAO.getCoursesForStudent(currentStudent.getStudentid());
        List<Scheduleblocks> scheduleblocks = new ArrayList<Scheduleblocks>();
        for (Courses course : courses) {
            scheduleblocks.add(ScheduleBlockDAO.getScheduleBlock(course.getScheduleblockid()));
        }
        Schools currentSchool = SchoolDAO.getSchool(currentStudent.getSchoolid());
        List<Schools> schoolyears = SchoolDAO.getSchoolSameName(currentSchool.getSchoolname());
        model.addAttribute("schoolyears", schoolyears);
        model.addAttribute("scheduleblocks", scheduleblocks);
        model.addAttribute("courses", courses);
        logger.info("Courses for this student added 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 "studenteditassigned";
}

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 a v  a2 s  .c  o m*/
 * "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:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/acceptaccount", method = RequestMethod.POST)
public String acceptAccount(Model model, @RequestParam(value = "email") String email) {
    try {//w w  w.j a  v a 2  s  . c o  m
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBAdminStudentAccts.log");
        logger.addHandler(handler);
        handler.setFormatter(new SimpleFormatter());
        StudentDAO.acceptAccount(email);
        Students student = StudentDAO.getStudent(email);
        EmailNotification.sendEmail(student.getEmail(), student.getFirstname());
        List<Students> accountrequests = StudentDAO.getAccountRequests();
        model.addAttribute("accountrequests", accountrequests);
        logger.info("Successfully accepted: " + email);
        logger.info("Account successfully updated to model");
        handler.close();
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "adminmanagerequests";

}

From source file:BSxSB.Controllers.AdminController.java

@RequestMapping(value = "/rejectaccount", method = RequestMethod.POST)
public String rejectAccount(Model model, @RequestParam(value = "email") String email) {
    try {//from  www  .  j  ava2 s .c om
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBAdminStudentAccts.log");
        logger.addHandler(handler);
        handler.setFormatter(new SimpleFormatter());
        StudentDAO.deleteAccount(email);
        List<Students> accountrequests = StudentDAO.getAccountRequests();
        model.addAttribute("accountrequests", accountrequests);
        logger.info("Successfully rejected: " + email);
        logger.info("Accounts successfully updated to model");
        handler.close();
    } catch (IOException ex) {
        logger.log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        logger.log(Level.SEVERE, null, ex);
    }
    return "adminmanagerequests";
}

From source file:BSxSB.Controllers.StudentController.java

@RequestMapping(value = "/removeassign", method = RequestMethod.POST)
public String removeAssigned(Model model, @RequestParam(value = "id") int id) {
    try {//from   w w w  .j  a v  a 2  s . co m
        //Initialize the file that the logger writes to.
        Handler handler = new FileHandler("%tBSxSBStudentAssignedCourses.log", true);
        handler.setFormatter(new SimpleFormatter());
        logger.addHandler(handler);
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String name = auth.getName();
        Students currentStudent = StudentDAO.getStudent(name);
        RegistrationDAO.removereg(id, currentStudent.getStudentid());
        CourseDAO.decrementCourseStudentsAndDelete(id);
        logger.info("Course successfully deleted");
        List<Courses> courses = CourseDAO.getCoursesForStudent(currentStudent.getStudentid());
        List<Scheduleblocks> scheduleblocks = new ArrayList<Scheduleblocks>();
        for (Courses course : courses) {
            scheduleblocks.add(ScheduleBlockDAO.getScheduleBlock(course.getScheduleblockid()));
        }
        Schools currentSchool = SchoolDAO.getSchool(currentStudent.getSchoolid());
        List<Schools> schoolyears = SchoolDAO.getSchoolSameName(currentSchool.getSchoolname());
        model.addAttribute("schoolyears", schoolyears);
        model.addAttribute("scheduleblocks", scheduleblocks);
        model.addAttribute("courses", courses);
        logger.info("Courses for this student added 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 "studenteditassigned";
}

From source file:com.diversityarrays.kdxplore.KDXplore.java

static private java.util.logging.Logger establishLogger(ApplicationFolder appFolder) {
    // Establish logger
    java.util.logging.Logger logger = null;

    try {//from ww  w .  j a  v a 2 s  . c o  m
        File applicationFolder = appFolder.getApplicationFolder();

        logger = Shared.Log.getLogger();
        if (logger == null) {
            String kdxploreLog = appFolder.getApplicationName().toLowerCase() + ".log"; //$NON-NLS-1$
            File logFile = new File(applicationFolder, kdxploreLog);
            if (logFile.exists()) {
                File bakFile = new File(applicationFolder, kdxploreLog + ".bak"); //$NON-NLS-1$
                if (bakFile.exists()) {
                    bakFile.delete();
                }
                logFile.renameTo(bakFile);
            }
            java.util.logging.FileHandler fh = new FileHandler(kdxploreLog);
            fh.setFormatter(new SimpleFormatter());
            logger = java.util.logging.Logger.getLogger(appFolder.getApplicationName());
            logger.addHandler(fh);
            Shared.Log.setLogger(logger);

            logger.info("==== Log Started ===="); //$NON-NLS-1$
        }

        ExplorerProperties.getInstance(applicationFolder);
    } catch (IOException e1) {
        JOptionPane.showMessageDialog(null, e1.getMessage(), "Unable to initialise environment", //$NON-NLS-1$
                JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    return logger;
}