List of usage examples for java.util.logging FileHandler FileHandler
public FileHandler(String pattern, boolean append) throws IOException, SecurityException
From source file:com.biggerbytes.scheduleupdates.Main.java
/** * //w w w .ja va 2 s.co m * @param args * @throws IOException */ public static void main(String[] args) throws IOException { java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); // In order to remove all the log warnings, THANK GOD IT IS THAT SIMPLE final int PORT = 25565; ServerSocket serverSocket = null; // Logger initialization if (LOG) { fh = new FileHandler("serv_log.log", true); //It will create a new file everytime we start the server because the previous log is locked, I am not really sure where to close the handler. logger.addHandler(fh); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); } // /* Dummy Test */ // List<Byte> command = new ArrayList<>(); // command.add(CommandConstants.SCEHDULES_HEADER); // command.add(CommandConstants.ADD_SUB_DUMMY); // command.add((byte) 24); // command.addAll(Arrays.asList(ArrayUtils.toObject("05".getBytes()))); // command.addAll(Arrays.asList(ArrayUtils.toObject("20.03.2016".getBytes()))); // command.addAll(Arrays.asList(ArrayUtils.toObject(" ".getBytes()))); // System.out.println("Size is " + command.size()); // byte[] commandArr = new byte[command.size()]; // for (int i = 0; i < commandArr.length; ++i) // commandArr[i] = command.get(i); // CommandProcessor.executeCommand(commandArr); /* Dummy Test End - TESTED, IT WORKS*/ /* Dummy removal */ // byte[] remvCommand = new byte[3]; // remvCommand[0] = CommandConstants.SCEHDULES_HEADER; // remvCommand[1] = CommandConstants.REMOVE_ALL_DUMMIES_FROM_ID; // remvCommand[2] = (byte) 24; // // CommandProcessor.executeCommand(remvCommand); // /* Dummy removal end - TESTED, WORKS*/ try { serverSocket = new ServerSocket(PORT); initDataRefreshThread(); infoReadThread.start(); } catch (Exception e) { if (LOG) logger.info("Couldn't listen on port " + PORT); System.exit(-1); } new CreateClientThread().start(); //Setup thread for creating threads for clients while (true) { System.out.println("waiting"); if (LOG) logger.info("Waiting for a client."); //TODO wait for the server to finish loading data then start waiting for a client Socket clientSocket = serverSocket.accept(); clientsQ.add(clientSocket); } }
From source file:edu.cmu.cs.lti.ark.fn.identification.training.AlphabetCreationThreaded.java
/** * Parses commandline args, then creates a new {@link #AlphabetCreationThreaded} with them * and calls {@link #createAlphabet}/*from w w w.j a v a 2 s . c o m*/ * * @param args commandline arguments. see {@link #AlphabetCreationThreaded} * for details. */ public static void main(String[] args) throws IOException, ClassNotFoundException, ExecutionException, InterruptedException { final FNModelOptions options = new FNModelOptions(args); LogManager.getLogManager().reset(); final FileHandler fileHandler = new FileHandler(options.logOutputFile.get(), true); fileHandler.setFormatter(new SimpleFormatter()); logger.addHandler(fileHandler); final int startIndex = options.startIndex.get(); final int endIndex = options.endIndex.get(); logger.info("Start:" + startIndex + " end:" + endIndex); final RequiredDataForFrameIdentification r = SerializedObjects.readObject(options.fnIdReqDataFile.get()); final int minimumCount = options.minimumCount.present() ? options.minimumCount.get() : DEFAULT_MINIMUM_FEATURE_COUNT; final int numThreads = options.numThreads.present() ? options.numThreads.get() : Runtime.getRuntime().availableProcessors(); final File alphabetDir = new File(options.modelFile.get()); final String featureExtractorType = options.idFeatureExtractorType.present() ? options.idFeatureExtractorType.get() : "basic"; final IdFeatureExtractor featureExtractor = IdFeatureExtractor.fromName(featureExtractorType); final AlphabetCreationThreaded events = new AlphabetCreationThreaded(options.trainFrameElementFile.get(), options.trainParseFile.get(), r.getFrameMap().keySet(), featureExtractor, startIndex, endIndex, numThreads); final Multiset<String> unconjoinedFeatures = events.createAlphabet(); final File alphabetFile = new File(alphabetDir, ALPHABET_FILENAME); events.conjoinAndWriteAlphabet(unconjoinedFeatures, minimumCount, alphabetFile); }
From source file:edu.cmu.cs.lti.ark.fn.identification.latentmodel.LatentAlphabetCreationThreaded.java
public static void main(String[] args) throws IOException, ClassNotFoundException { final FNModelOptions options = new FNModelOptions(args); LogManager.getLogManager().reset(); final FileHandler fileHandler = new FileHandler(options.logOutputFile.get(), true); fileHandler.setFormatter(new SimpleFormatter()); logger.addHandler(fileHandler);/* w w w . j a v a 2s . c o m*/ final int startIndex = options.startIndex.get(); final int endIndex = options.endIndex.get(); logger.info("Start:" + startIndex + " end:" + endIndex); final RequiredDataForFrameIdentification r = SerializedObjects.readObject(options.fnIdReqDataFile.get()); final Relations wnRelations = new CachedRelations(r.getRevisedRelMap(), r.getRelatedWordsForWord()); final Lemmatizer lemmatizer = new CachedLemmatizer(r.getHvLemmaCache()); final int numThreads = options.numThreads.present() ? options.numThreads.get() : Runtime.getRuntime().availableProcessors(); final File alphabetDir = new File(options.modelFile.get()); final LatentAlphabetCreationThreaded events = new LatentAlphabetCreationThreaded(alphabetDir, options.trainFrameElementFile.get(), options.trainParseFile.get(), r.getFrameMap(), new LatentFeatureExtractor(wnRelations, lemmatizer), startIndex, endIndex, numThreads); events.createLocalAlphabets(); combineAlphabets(alphabetDir); }
From source file:edu.cmu.cs.lti.ark.fn.identification.latentmodel.TrainBatchModelDerThreaded.java
public static void main(String[] args) throws Exception { final FNModelOptions options = new FNModelOptions(args); LogManager.getLogManager().reset(); final FileHandler fh = new FileHandler(options.logOutputFile.get(), true); fh.setFormatter(new SimpleFormatter()); logger.addHandler(fh);/*from w w w.j a v a2s. co m*/ final String restartFile = options.restartFile.get(); final int numThreads = options.numThreads.present() ? options.numThreads.get() : Runtime.getRuntime().availableProcessors(); final TrainBatchModelDerThreaded tbm = new TrainBatchModelDerThreaded(options.alphabetFile.get(), options.eventsFile.get(), options.modelFile.get(), options.reg.get(), options.lambda.get(), restartFile.equals("null") ? Optional.<String>absent() : Optional.of(restartFile), numThreads); tbm.trainModel(); }
From source file:net.oneandone.sushi.fs.webdav.WebdavFilesystem.java
public static void wireLog(String file) { Handler handler;/* w w w . j a v a 2 s .c o m*/ WIRE.setLevel(Level.FINE); 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:util.Log.java
/** * Gera um arquivo log dentro da Pasta Logger que fica na Pasta principal do * Usuario.//from w w w .ja v a2 s . c o m * * @param className * @param ex */ public static void relatarExcecao(String className, Exception ex) { try { /* * Informamos qual o nome do Logger, que no caso vai ser o nome da * Classe que acontecer a exceo */ Logger log = Logger.getLogger(className); /* * Variavel que vai conter qual a pasta do sistema que liga ao * usuario, por padro ser do sistema operacional Windows */ String systemPath = "/Users/"; /* Se for outro sistema operacional */ if (System.getProperty("os.name").startsWith("Linux")) { systemPath = "/home/"; } /* Pasta onde vamos colocar os Logs */ File pastaLog = new File(systemPath + System.getProperty("user.name") + "/Logger"); if (!pastaLog.exists()) { pastaLog.mkdir(); } String arquivoDir = pastaLog.getAbsolutePath() + "/LOG_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd-MM_HH-mm-ss")) + ".log"; /* Classe responsavel por escrever o arquivo */ FileHandler escrever = new FileHandler(arquivoDir, true); /* * Precisamos informar como ser escrito(formato) as excees, Vamos * Utilizar uma Classe j pronta para isso a Classe SimpleFormatter */ escrever.setFormatter(new SimpleFormatter()); /* * Adicionamos ao nosso log a Classe que vai escrever a exceo que * for gerada */ log.addHandler(escrever); /* * Geramos o Log, passamos que ser de Nivel Severe(Alto), e * passamos a exceo para ele */ log.log(Level.SEVERE, null, ex); /* Finalizamos a escrita */ escrever.flush(); escrever.close(); /*Envia por email a exceo*/ Log.relatarExceptionEmail(className, ex.getMessage(), arquivoDir); } catch (IOException | SecurityException e) { Logger.getLogger(Log.class.getName()).log(Level.SEVERE, null, e); } }
From source file:uk.nhs.cfh.dsp.srth.distribution.TRUDLoginService.java
public TRUDLoginService(FTPClient ftpClient) { this.ftpClient = ftpClient; try {//from w w w . j a v a 2s . c o m logger.addHandler(new FileHandler(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "configurator.log", true)); } catch (IOException e) { logger.warning("Nested exception is : " + e.fillInStackTrace().getMessage()); } }
From source file:BSxSB.Controllers.AdminController.java
@RequestMapping(value = "/admin", method = RequestMethod.GET) public String adminPage(Model model) { try {/*from ww w. j a va 2 s .c o m*/ 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:com.sustainalytics.crawlerfilter.PDFtoTextBatch.java
/** * Method to initiate logger// www. j a va2 s.c o m * @param file is a File object. The log file will be placed in this file's folder */ public static void initiateLogger(File file) { FileHandler fileHandler; try { // This block configure the logger with handler and formatter fileHandler = new FileHandler(file.getAbsolutePath() + "/" + "log.txt", true); logger.addHandler(fileHandler); SimpleFormatter formatter = new SimpleFormatter(); fileHandler.setFormatter(formatter); } catch (SecurityException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
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 {/*w w w .j a va2 s . co 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) { } ; } }