Java Code Examples for java.util.logging.FileHandler

The following examples show how to use java.util.logging.FileHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: ignite   Source File: CommandHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return prepared JULs logger.
 */
private Logger setupJavaLogger() {
    Logger result = initLogger(CommandHandler.class.getName() + "Log");

    // Adding logging to file.
    try {
        String absPathPattern = new File(JavaLoggerFileHandler.logDirectory(U.defaultWorkDirectory()), "control-utility-%g.log").getAbsolutePath();

        FileHandler fileHandler = new FileHandler(absPathPattern, 5 * 1024 * 1024, 5);

        fileHandler.setFormatter(new JavaLoggerFormatter());

        result.addHandler(fileHandler);
    }
    catch (Exception e) {
        System.out.println("Failed to configure logging to file");
    }

    // Adding logging to console.
    result.addHandler(setupStreamHandler());

    return result;
}
 
Example 2
private static void testFileHandlerClose(File writableDir) throws IOException {
    File fakeLock = new File(writableDir, "log.log.lck");
    if (!createFile(fakeLock, false)) {
        throw new IOException("Can't create fake lock file: " + fakeLock);
    }
    try {
        List<File> before = listLocks(writableDir, true);
        System.out.println("before: " + before.size() + " locks found");
        FileHandler handler = createFileHandler(writableDir);
        System.out.println("handler created: " + handler);
        List<File> after = listLocks(writableDir, true);
        System.out.println("after creating handler: " + after.size() + " locks found");
        handler.close();
        System.out.println("handler closed: " + handler);
        List<File> afterClose = listLocks(writableDir, true);
        System.out.println("after closing handler: " + afterClose.size() + " locks found");
        afterClose.removeAll(before);
        if (!afterClose.isEmpty()) {
            throw new RuntimeException("Zombie lock file detected: " + afterClose);
        }
    } finally {
        if (fakeLock.canRead()) delete(fakeLock);
    }
    List<File> finalLocks = listLocks(writableDir, false);
    System.out.println("After cleanup: " + finalLocks.size() + " locks found");
}
 
Example 3
public static void main(String[] args) throws Exception {
    String maxLocksSet = System.getProperty(MX_LCK_SYS_PROPERTY);
    File loggerDir = createLoggerDir();
    List<FileHandler> fileHandlers = new ArrayList<>();
    try {
        // 200 raises the default limit of 100, we try 102 times
        for (int i = 0; i < 102; i++) {
            fileHandlers.add(new FileHandler(loggerDir.getPath()
                    + File.separator + "test_%u.log"));
        }
    } catch (IOException ie) {
        if (maxLocksSet.equals("200ab")
                && ie.getMessage().contains("get lock for")) {
            // Ignore: Expected exception while passing bad value- 200ab
        } else {
            throw new RuntimeException("Test Failed: " + ie.getMessage());
        }
    } finally {
        for (FileHandler fh : fileHandlers) {
            fh.close();
        }
        FileUtils.deleteFileTreeWithRetry(Paths.get(loggerDir.getPath()));
    }
}
 
Example 4
private static void testFileHandlerClose(File writableDir) throws IOException {
    File fakeLock = new File(writableDir, "log.log.lck");
    if (!createFile(fakeLock, false)) {
        throw new IOException("Can't create fake lock file: " + fakeLock);
    }
    try {
        List<File> before = listLocks(writableDir, true);
        System.out.println("before: " + before.size() + " locks found");
        FileHandler handler = createFileHandler(writableDir);
        System.out.println("handler created: " + handler);
        List<File> after = listLocks(writableDir, true);
        System.out.println("after creating handler: " + after.size() + " locks found");
        handler.close();
        System.out.println("handler closed: " + handler);
        List<File> afterClose = listLocks(writableDir, true);
        System.out.println("after closing handler: " + afterClose.size() + " locks found");
        afterClose.removeAll(before);
        if (!afterClose.isEmpty()) {
            throw new RuntimeException("Zombie lock file detected: " + afterClose);
        }
    } finally {
        if (fakeLock.canRead()) delete(fakeLock);
    }
    List<File> finalLocks = listLocks(writableDir, false);
    System.out.println("After cleanup: " + finalLocks.size() + " locks found");
}
 
Example 5
private static void testFileHandlerCreate(File writableDir, boolean first)
        throws IOException {
    List<File> before = listLocks(writableDir, true);
    System.out.println("before: " + before.size() + " locks found");
    try {
        if (first && !before.isEmpty()) {
            throw new RuntimeException("Expected no lock file! Found: " + before);
        } else if (!first && before.size() != 1) {
            throw new RuntimeException("Expected a single lock file! Found: " + before);
        }
    } finally {
        before.stream().forEach(CheckZombieLockTest::delete);
    }
    FileHandler handler = createFileHandler(writableDir);
    System.out.println("handler created: " + handler);
    List<File> after = listLocks(writableDir, true);
    System.out.println("after creating handler: " + after.size() + " locks found");
    if (after.size() != 1) {
        throw new RuntimeException("Unexpected number of lock files found for "
                + handler + ": " + after);
    }
}
 
Example 6
public static void main(String[] args) throws Exception {
    String maxLocksSet = System.getProperty(MX_LCK_SYS_PROPERTY);
    File loggerDir = createLoggerDir();
    List<FileHandler> fileHandlers = new ArrayList<>();
    try {
        // 200 raises the default limit of 100, we try 102 times
        for (int i = 0; i < 102; i++) {
            fileHandlers.add(new FileHandler(loggerDir.getPath()
                    + File.separator + "test_%u.log"));
        }
    } catch (IOException ie) {
        if (maxLocksSet.equals("200ab")
                && ie.getMessage().contains("get lock for")) {
            // Ignore: Expected exception while passing bad value- 200ab
        } else {
            throw new RuntimeException("Test Failed: " + ie.getMessage());
        }
    } finally {
        for (FileHandler fh : fileHandlers) {
            fh.close();
        }
        FileUtils.deleteFileTreeWithRetry(Paths.get(loggerDir.getPath()));
    }
}
 
Example 7
Source Project: jdk8u60   Source File: CheckZombieLockTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void testFileHandlerCreate(File writableDir, boolean first)
        throws IOException {
    List<File> before = listLocks(writableDir, true);
    System.out.println("before: " + before.size() + " locks found");
    try {
        if (first && !before.isEmpty()) {
            throw new RuntimeException("Expected no lock file! Found: " + before);
        } else if (!first && before.size() != 1) {
            throw new RuntimeException("Expected a single lock file! Found: " + before);
        }
    } finally {
        before.stream().forEach(CheckZombieLockTest::delete);
    }
    FileHandler handler = createFileHandler(writableDir);
    System.out.println("handler created: " + handler);
    List<File> after = listLocks(writableDir, true);
    System.out.println("after creating handler: " + after.size() + " locks found");
    if (after.size() != 1) {
        throw new RuntimeException("Unexpected number of lock files found for "
                + handler + ": " + after);
    }
}
 
Example 8
private static void testFileHandlerClose(File writableDir) throws IOException {
    File fakeLock = new File(writableDir, "log.log.lck");
    if (!createFile(fakeLock, false)) {
        throw new IOException("Can't create fake lock file: " + fakeLock);
    }
    try {
        List<File> before = listLocks(writableDir, true);
        System.out.println("before: " + before.size() + " locks found");
        FileHandler handler = createFileHandler(writableDir);
        System.out.println("handler created: " + handler);
        List<File> after = listLocks(writableDir, true);
        System.out.println("after creating handler: " + after.size() + " locks found");
        handler.close();
        System.out.println("handler closed: " + handler);
        List<File> afterClose = listLocks(writableDir, true);
        System.out.println("after closing handler: " + afterClose.size() + " locks found");
        afterClose.removeAll(before);
        if (!afterClose.isEmpty()) {
            throw new RuntimeException("Zombie lock file detected: " + afterClose);
        }
    } finally {
        if (fakeLock.canRead()) delete(fakeLock);
    }
    List<File> finalLocks = listLocks(writableDir, false);
    System.out.println("After cleanup: " + finalLocks.size() + " locks found");
}
 
Example 9
private static void testFileHandlerClose(File writableDir) throws IOException {
    File fakeLock = new File(writableDir, "log.log.lck");
    if (!createFile(fakeLock, false)) {
        throw new IOException("Can't create fake lock file: " + fakeLock);
    }
    try {
        List<File> before = listLocks(writableDir, true);
        System.out.println("before: " + before.size() + " locks found");
        FileHandler handler = createFileHandler(writableDir);
        System.out.println("handler created: " + handler);
        List<File> after = listLocks(writableDir, true);
        System.out.println("after creating handler: " + after.size() + " locks found");
        handler.close();
        System.out.println("handler closed: " + handler);
        List<File> afterClose = listLocks(writableDir, true);
        System.out.println("after closing handler: " + afterClose.size() + " locks found");
        afterClose.removeAll(before);
        if (!afterClose.isEmpty()) {
            throw new RuntimeException("Zombie lock file detected: " + afterClose);
        }
    } finally {
        if (fakeLock.canRead()) delete(fakeLock);
    }
    List<File> finalLocks = listLocks(writableDir, false);
    System.out.println("After cleanup: " + finalLocks.size() + " locks found");
}
 
Example 10
private static void testFileHandlerCreate(File writableDir, boolean first)
        throws IOException {
    List<File> before = listLocks(writableDir, true);
    System.out.println("before: " + before.size() + " locks found");
    try {
        if (first && !before.isEmpty()) {
            throw new RuntimeException("Expected no lock file! Found: " + before);
        } else if (!first && before.size() != 1) {
            throw new RuntimeException("Expected a single lock file! Found: " + before);
        }
    } finally {
        before.stream().forEach(CheckZombieLockTest::delete);
    }
    FileHandler handler = createFileHandler(writableDir);
    System.out.println("handler created: " + handler);
    List<File> after = listLocks(writableDir, true);
    System.out.println("after creating handler: " + after.size() + " locks found");
    if (after.size() != 1) {
        throw new RuntimeException("Unexpected number of lock files found for "
                + handler + ": " + after);
    }
}
 
Example 11
Source Project: uima-uimaj   Source File: PMController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Enables/disables PM log file. By default, the log file is disabled.
 * 
 * @param enable
 *          if <code>true</code>, the log file is enabled, otherwise it is disabled.
 */
public static void setLogFileEnabled(boolean enable) {
  if (enable) {
    Handler[] handlers = getLogger().getHandlers();
    if (handlers == null || handlers.length == 0) {
      // add default file handler
      try {
        FileHandler fileHandler = new FileHandler(LOG_FILE, false);
        fileHandler.setLevel(Level.ALL);
        fileHandler.setFormatter(new PMLogFormatter());
        getLogger().addHandler(fileHandler);
      } catch (Throwable err) {
        System.err.println("Error initializing log file " + PMController.class.getName() + ": "
                + err.toString());
      }
    }
  }
  __logFileEnabled = enable;
}
 
Example 12
/**
    * Creates a static {@code Logger} instance.
    *
    * @return a static {@code Logger} with properties:
    *         <ul>
    *         <li>Name: {@code "DefaultDatabaseConfigurator"}.</li>
    *         <li>Output file pattern:
    *         {@code user.home/.kawansoft/log/AceQL.log}.</li>
    *         <li>Formatter: {@code SimpleFormatter}.</li>
    *         <li>Limit: 200Mb.</li>
    *         <li>Count (number of files to use): 2.</li>
    *         </ul>
    */
   @Override
   public Logger getLogger() throws IOException {
if (ACEQL_LOGGER != null) {
    return ACEQL_LOGGER;
}

File logDir = new File(SystemUtils.USER_HOME + File.separator + ".kawansoft" + File.separator + "log");
logDir.mkdirs();

String pattern = logDir.toString() + File.separator + "AceQL.log";

ACEQL_LOGGER = Logger.getLogger(DefaultDatabaseConfigurator.class.getName());
Handler fh = new FileHandler(pattern, 200 * 1024 * 1024, 2, true);
fh.setFormatter(new NoFormatter());
ACEQL_LOGGER.addHandler(fh);
return ACEQL_LOGGER;

   }
 
Example 13
private static void testFileHandlerCreate(File writableDir, boolean first)
        throws IOException {
    List<File> before = listLocks(writableDir, true);
    System.out.println("before: " + before.size() + " locks found");
    try {
        if (first && !before.isEmpty()) {
            throw new RuntimeException("Expected no lock file! Found: " + before);
        } else if (!first && before.size() != 1) {
            throw new RuntimeException("Expected a single lock file! Found: " + before);
        }
    } finally {
        before.stream().forEach(CheckZombieLockTest::delete);
    }
    FileHandler handler = createFileHandler(writableDir);
    System.out.println("handler created: " + handler);
    List<File> after = listLocks(writableDir, true);
    System.out.println("after creating handler: " + after.size() + " locks found");
    if (after.size() != 1) {
        throw new RuntimeException("Unexpected number of lock files found for "
                + handler + ": " + after);
    }
}
 
Example 14
public static void test(String name, Properties props, long limit) throws Exception {
    System.out.println("Testing: " + name);
    Class<? extends Exception> expectedException = null;

    if (userDirWritable || expectedException != null) {
        // These calls will create files in user.dir.
        // The file name contain a random UUID (PREFIX) which identifies them
        // and allow us to remove them cleanly at the end (see finally block
        // in main()).
        checkException(expectedException, () -> new FileHandler());
        checkException(expectedException, () -> {
            final FileHandler fh = new FileHandler();
            assertEquals(limit, getLimit(fh), "limit");
            return fh;
        });
        checkException(expectedException, () -> testFileHandlerLimit(
                () -> new FileHandler(),
                limit));
        checkException(expectedException, () -> testFileHandlerLimit(
                () -> new FileHandler(PREFIX, Long.MAX_VALUE, 1, true),
                Long.MAX_VALUE));
    }
}
 
Example 15
private static void testFileHandlerCreate(File writableDir, boolean first)
        throws IOException {
    List<File> before = listLocks(writableDir, true);
    System.out.println("before: " + before.size() + " locks found");
    try {
        if (first && !before.isEmpty()) {
            throw new RuntimeException("Expected no lock file! Found: " + before);
        } else if (!first && before.size() != 1) {
            throw new RuntimeException("Expected a single lock file! Found: " + before);
        }
    } finally {
        before.stream().forEach(CheckZombieLockTest::delete);
    }
    FileHandler handler = createFileHandler(writableDir);
    System.out.println("handler created: " + handler);
    List<File> after = listLocks(writableDir, true);
    System.out.println("after creating handler: " + after.size() + " locks found");
    if (after.size() != 1) {
        throw new RuntimeException("Unexpected number of lock files found for "
                + handler + ": " + after);
    }
}
 
Example 16
Source Project: Analyze   Source File: AuditFileWriter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Create and configure a FileHandler to use for writing to the audit log.
 * @param config configuration properties.
 * @throws RuntimeException if the log file cannot be opened for writing.
 */
private FileHandler createFileHandler(final FileConfiguration config)
{
    try
    {
        // Specify append mode to avoid previous audit logs being overwritten.
        return new FileHandler(config.getFileName(),
                config.getSizeLimit(),
                config.getFileCount(),
                true);
    }
    catch (SecurityException | IOException ex)
    {
        throw new RuntimeException("Failed to open log file: " + config.getFileName(), ex);
    }
}
 
Example 17
Source Project: RegexGenerator   Source File: Main.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws TreeEvaluationException, IOException, Exception {
    if (args.length < 1) {
        printUsage();
        System.exit(0);
    }


    Configuration configuration = Configurator.configure(args[0]);
    //Configuration configuration = new Configuration();
       
    Logger.getLogger("").addHandler(new FileHandler(new File(configuration.getOutputFolder(), "log.xml").getCanonicalPath()));
    Results results = new Results(configuration);
    results.setMachineHardwareSpecifications(Utils.cpuInfo());

    ExecutionStrategy strategy = configuration.getStrategy();
    long startTime = System.currentTimeMillis();
    
    strategy.execute(configuration, new CoolTextualExecutionListener(args[0], configuration, results));
    
    if (configuration.getPostProcessor() != null) {
        startTime = System.currentTimeMillis() - startTime;
        configuration.getPostProcessor().elaborate(configuration, results, startTime);
    }

}
 
Example 18
Source Project: OCA-Java-SE-7-Programmer-I   Source File: TestClass.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException {

        /* Ensure directory has been created */
        new File("logs").mkdir();

        /* Get the date to be used in the filename */
        DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
        Date now = new Date();
        String date = df.format(now);

        /* Set up the filename in the logs directory */
        String logFileName = "logs/testlog-" + date + ".txt";

        /* Set up logger */
        FileHandler myFileHandler = new FileHandler(logFileName);
        myFileHandler.setFormatter(new SimpleFormatter());
        Logger ocajLogger = Logger.getLogger("OCAJ Logger");
        ocajLogger.setLevel(Level.ALL);
        ocajLogger.addHandler(myFileHandler);

        /* Log Message */
        ocajLogger.info("\nThis is a logged information message.");

        /* Close the file */
        myFileHandler.close();
    }
 
Example 19
Source Project: gemfirexd-oss   Source File: GemFireXDDataExtractorImpl.java    License: Apache License 2.0 6 votes vote down vote up
protected void configureLogger() throws SecurityException, IOException {
  if (logger == null) {
    logger = Logger.getLogger(LOGGER_NAME);
  }
  logger.setUseParentHandlers(false);
  logFileHandler = new FileHandler(logFilePath);
  logFileHandler.setFormatter(new SimpleFormatter());
  Level logLevel = Level.INFO;
  try {
    logLevel = Level.parse(logLevelString);
  } catch (IllegalArgumentException e) {
    logInfo("Unrecognized log level :" + logLevelString + " defaulting to :" + logLevel);
  }
  logFileHandler.setLevel(logLevel);
  logger.addHandler(logFileHandler);
}
 
Example 20
private static FileHandler createFileHandler(File writableDir) throws SecurityException,
        RuntimeException, IOException {
    // Test 1: make sure we can create FileHandler in writable directory
    try {
        FileHandler handler = new FileHandler("%t/" + WRITABLE_DIR + "/log.log");
        handler.publish(new LogRecord(Level.INFO, handler.toString()));
        handler.flush();
        return handler;
    } catch (IOException ex) {
        throw new RuntimeException("Test failed: should have been able"
                + " to create FileHandler for " + "%t/" + WRITABLE_DIR
                + "/log.log in writable directory.", ex);
    }
}
 
Example 21
/**
 * Main entry point for the OpenOffice.org Bean Test.
 *
 * @param args arguments of the test
 *
 * @author Andreas Bröker
 * @date 21.05.2006
 */
public static void main(String[] args) throws OfficeApplicationException {

   LogManager.getLogManager().reset();
   ConsoleHandler consoleHandler = new ConsoleHandler();
   consoleHandler.setLevel(Level.FINEST);
   LOGGER.addHandler(consoleHandler);
   LOGGER.setLevel(Level.FINEST);

   try {
      FileHandler fileHandler = new FileHandler("log.xml");
      fileHandler.setLevel(Level.FINEST);
      LOGGER.addHandler(fileHandler);
   } catch (Throwable throwable) {
   }
   OfficeBeanTest testOfficeBean = new OfficeBeanTest();

   if (args.length == 0) {
      testOfficeBean.test(null);
   }else if (args.length == 1) {
      testOfficeBean.test(args[0]);
   }else if(args.length==4){
      testOfficeBean.remoteTestPDF(new File(args[2]), new File(args[3]), args[0], Integer.valueOf(args[1]));
   }else{
      System.out.println("usage:\nOfficeBeanTest host port source-odt target-pdf\nOfficeBeanTest officeHome");
   }
}
 
Example 22
Source Project: gitlab4j-api   Source File: TestRequestResponseLogging.java    License: MIT License 5 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {

    String problems = "";

    if (TEST_HOST_URL == null || TEST_HOST_URL.trim().isEmpty()) {
        problems += "TEST_HOST_URL cannot be empty\n";
    }

    if (TEST_PRIVATE_TOKEN == null || TEST_PRIVATE_TOKEN.trim().isEmpty()) {
        problems += "TEST_PRIVATE_TOKEN cannot be empty\n";
    }

    if (problems.isEmpty()) {

        tempLoggingFile = tempFolder.newFile("test-loging.log");

        loggingHandler = new FileHandler(tempLoggingFile.getAbsolutePath());
        loggingHandler.setFormatter(new SimpleFormatter());
        logger = Logger.getLogger(TestRequestResponseLogging.class.getName());
        logger.setUseParentHandlers(false);
        logger.addHandler(loggingHandler);
        loggingHandler.setLevel(Level.ALL);
        logger.setLevel(Level.ALL);

        gitLabApiWithEntityLogging = new GitLabApi(TEST_HOST_URL, TEST_PRIVATE_TOKEN);
        gitLabApiWithEntityLogging.enableRequestResponseLogging(logger, Level.INFO, 100);
        gitLabApiNoEntityLogging = new GitLabApi(TEST_HOST_URL, TEST_PRIVATE_TOKEN);
        gitLabApiNoEntityLogging.enableRequestResponseLogging(logger, Level.INFO);
        gitLabApiNoMaskingLogging = new GitLabApi(TEST_HOST_URL, TEST_PRIVATE_TOKEN);
        gitLabApiNoMaskingLogging.enableRequestResponseLogging(logger, Level.INFO, 100, new ArrayList<String>());

        gitLabApiWithoutLogging = new GitLabApi(TEST_HOST_URL, TEST_PRIVATE_TOKEN);

    } else {
        System.err.print(problems);
    }
}
 
Example 23
Source Project: birt   Source File: EngineLoggerTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * the user uses the user defined log. All log should be outputted to the
 * user defined logger.
 * 
 * @throws Exception
 */
public void testUserLogger( ) throws Exception
{
	// init the root logger
	FileHandler fileHandle = new FileHandler( "./utest/logger.txt" );
	try
	{
		Logger logger = Logger.getAnonymousLogger( );
		logger.addHandler( fileHandle );
		logger.setLevel( Level.ALL );
		logger.setUseParentHandlers( false );
		try
		{

			// start a default logger
			LoggerSetting setting = EngineLogger.createSetting(logger, null, null, Level.FINE, 0, 0);

			// all the log should be output to the root logger
			log( );
			EngineLogger.setLogger( setting, null );
			log( );
			EngineLogger.removeSetting(setting);
		}
		finally
		{
			logger.removeHandler( fileHandle );
		}
	}
	finally
	{
		fileHandle.close( );
	}
	// test the log file content
	checkLogging( "./utest/logger.txt", 0, 1, 1 );
}
 
Example 24
Source Project: android-uiconductor   Source File: UicdCLI.java    License: Apache License 2.0 5 votes vote down vote up
private static void setRedirectOutputToFile(Path logFolder) throws IOException {
  Path logFilePath =
      Paths.get(logFolder.toString(), LOG_FILENAME_PREFIX + new Date().getTime() + ".txt");
  System.out.println("Starting print to file...\n" + logFilePath.toString());
  Handler fh = new FileHandler(logFilePath.toString());
  fh.setFormatter(new SimpleFormatter());

  // Remove the output in the console.
  LogManager.getLogManager().reset();
  Logger.getLogger("uicd").addHandler(fh);
}
 
Example 25
Source Project: phoenix   Source File: IndexUpgradeTool.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public void prepareToolSetup() {
    try {
        if (logFile != null) {
            FileHandler fh = new FileHandler(logFile);
            fh.setFormatter(new SimpleFormatter());
            LOGGER.addHandler(fh);
        }

        prop.put(Indexer.INDEX_BUILDER_CONF_KEY, PhoenixIndexBuilder.class.getName());
        prop.put(NonTxIndexBuilder.CODEC_CLASS_NAME_KEY, PhoenixIndexCodec.class.getName());

        if (inputTables == null) {
            inputTables = new String(Files.readAllBytes(Paths.get(inputFile)));
        }
        if (inputTables == null) {
            LOGGER.severe("Tables' list is not available; use -tb or -f option");
        }
        LOGGER.info("list of tables passed: " + inputTables);

        if (operation.equalsIgnoreCase(UPGRADE_OP)) {
            upgrade = true;
        } else if (operation.equalsIgnoreCase(ROLLBACK_OP)) {
            upgrade = false;
        } else {
            throw new IllegalStateException("Invalid option provided for "
                    + OPERATION_OPTION.getOpt() + " expected values: {upgrade, rollback}");
        }
        if (dryRun) {
            LOGGER.info("This is the beginning of the tool with dry run.");
        }
    } catch (IOException e) {
        LOGGER.severe("Something went wrong " + e);
        System.exit(-1);
    }
}
 
Example 26
Source Project: oodt   Source File: PGETaskInstance.java    License: Apache License 2.0 5 votes vote down vote up
protected java.util.logging.Logger createLogger() throws IOException, PGEException {
   File logDir = new File(pgeConfig.getExeDir(), "logs");
   if (!(logDir.exists() || logDir.mkdirs())) {
      throw new PGEException("mkdirs for logs directory return false");
   }

   java.util.logging.Logger logger = java.util.logging.Logger.getLogger(PGETaskInstance.class.getName() + "." + workflowInstId);
   // TODO Need to find an alternative way to add a dynamic handler to write workflowInstance logs to a separate file
   FileHandler handler = new FileHandler(new File(logDir, createLogFileName()).getAbsolutePath());
   handler.setEncoding("UTF-8");
   handler.setFormatter(new SimpleFormatter());
   logger.addHandler(handler);
   return logger;
}
 
Example 27
private static FileHandler createFileHandler(File writableDir) throws SecurityException,
        RuntimeException, IOException {
    // Test 1: make sure we can create FileHandler in writable directory
    try {
        FileHandler handler = new FileHandler("%t/" + WRITABLE_DIR + "/log.log");
        handler.publish(new LogRecord(Level.INFO, handler.toString()));
        handler.flush();
        return handler;
    } catch (IOException ex) {
        throw new RuntimeException("Test failed: should have been able"
                + " to create FileHandler for " + "%t/" + WRITABLE_DIR
                + "/log.log in writable directory.", ex);
    }
}
 
Example 28
Source Project: otroslogviewer   Source File: OtrosLogViewerBaseTest.java    License: Apache License 2.0 5 votes vote down vote up
public void logEvents(File file, int count, Function<Integer, Level> levelGenerator) throws IOException {
  final Logger logger = Logger.getLogger("some logger");
  logger.setUseParentHandlers(false);
  logger.addHandler(new FileHandler(file.getAbsolutePath()));
  IntStream
    .range(0, count)
    .forEach(i -> logger.log(levelGenerator.apply(i), "Message " + i));
}
 
Example 29
Source Project: jdk8u60   Source File: CheckZombieLockTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static FileHandler createFileHandler(File writableDir) throws SecurityException,
        RuntimeException, IOException {
    // Test 1: make sure we can create FileHandler in writable directory
    try {
        FileHandler handler = new FileHandler("%t/" + WRITABLE_DIR + "/log.log");
        handler.publish(new LogRecord(Level.INFO, handler.toString()));
        handler.flush();
        return handler;
    } catch (IOException ex) {
        throw new RuntimeException("Test failed: should have been able"
                + " to create FileHandler for " + "%t/" + WRITABLE_DIR
                + "/log.log in writable directory.", ex);
    }
}
 
Example 30
Source Project: authlib-agent   Source File: Transformer.java    License: MIT License 5 votes vote down vote up
public synchronized void debugOn(){
	if (debugMode){
		return;
	}
	debugMode=true;
	try {
		logger.addHandler(new FileHandler("authlibagent.log"));
	} catch (SecurityException | IOException e) {
		logger.severe("failed to add file handler" + e);
		e.printStackTrace();
	}
}