public Server(String fileName, boolean restart) { super(); parseServerFile(fileName); seatAssignments = new ArrayList<>(nSeats); for (int i = 0; i < nSeats; i++) seatAssignments.add(""); log.getParent().removeHandler(log.getParent().getHandlers()[0]); try { // check if logs dir exists File logDir = new File("./logs/"); if( !(logDir.exists()) ) logDir.mkdir(); FileHandler fh = new FileHandler("logs/server_log_" + serverID + ".log"); fh.setFormatter(new SimpleFormatter()); fh.setLevel(logLevel); log.addHandler(fh); ConsoleHandler ch = new ConsoleHandler(); ch.setLevel(logLevel); log.addHandler(ch); log.setLevel(logLevel); log.info("Server initializing..."); log.info("ServerID = " + serverID); log.info("nServers = " + nServers); log.info("nSeats = " + nSeats); log.info("my tcp port = " + tcpPort); for (int i = 0; i < nServers; i++) log.info("Server " + i + ": " + servers.get(i) + ":" + ports.get(i)); log.info("Server init complete"); log.info("--------------------------------"); mutex = new LamportMutex(servers, ports, this, restart); mutex.init(); } catch (SecurityException | IOException e) { e.printStackTrace(); } }
private AptaLogger() throws IOException{ //instance the file handler filepath = Paths.get(Configuration.getParameters().getString("Experiment.projectPath"), "log_" + formatter.format(new Date()) + ".txt").toString(); fileHandler = new FileHandler(filepath,true); fileHandler.setLevel(Level.ALL); // We want everything logged on file //instance the logger logger = Logger.getLogger(AptaLogger.class.getName()); logger.setUseParentHandlers(false); logger.setLevel(Level.ALL); //instance formatter, set formatting, and handler formatterTxt = new AptaLoggerFormat(); fileHandler.setFormatter(formatterTxt); logger.addHandler(fileHandler); }
private LogService(Logger logger) { super(logger); // setup a log file if the execution mode can access the filesystem (e.g. not for RA) // we want our logfile to look the same regardless of any user settings, so ignore // a possible user logging property config file if (RapidMiner.getExecutionMode().canAccessFilesystem()) { try { FileHandler logFileHandler = new FileHandler(FileSystemService.getLogFile().getAbsolutePath(), false); logFileHandler.setLevel(Level.ALL); logFileHandler.setFormatter(new SimpleFormatter()); LogService.getRoot().addHandler(logFileHandler); } catch (IOException e) { LogService.getRoot().log(Level.WARNING, "com.rapidminer.logservice.logfile.failed_to_init", e.getMessage()); } } }
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"); }
/** * Initializes all globals to a default state. Used so that in the case of a * memory leak, the previous values are not accidentally used. */ public static void initGlobals() { System.setProperty("java.util.logging.SimpleFormatter.format", "(%1$tc) [%4$s] ~%2$s~%nMessage: \"%5$s\"%n"); try { handler = new FileHandler("log.txt"); handler.setLevel(Level.INFO); handler.setFormatter(new SimpleFormatter()); // Ensure we only log to log file. LOGGER.setUseParentHandlers(false); LOGGER.addHandler(handler); LOGGER.setLevel(Level.INFO); } catch (IOException | SecurityException ex) { throw new RuntimeException("Failed to initialized logger... " + ex.getMessage()); } PROJECT_FOLDER = null; URI_PREFIX = null; CURRENT_FILE = null; }
public static void main(String[] args) { try { LogManager lm = LogManager.getLogManager(); Logger logger = Logger.getLogger("BasicLogging"); FileHandler fh = new FileHandler("log_test.txt"); lm.addLogger(logger); logger.addHandler(fh); logger.log(Level.INFO, "test 1"); logger.log(Level.INFO, "test 2"); fh.close(); } catch (Exception e) { System.err.println("Exception thrown: " + e); e.printStackTrace(); } }
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); }
public static void main(String[] args) throws SecurityException, IOException { Logger logger = Logger.getGlobal(); logger.setLevel(Level.FINER); System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tF %1$tT %4$s %2$s %5$s%6$s%n"); SimpleFormatter formatterTxt = new SimpleFormatter(); FileHandler logFile = new FileHandler("log2.txt"); logFile.setLevel(Level.FINER); logFile.setFormatter(formatterTxt); logger.addHandler(logFile); // Create and set handler Handler systemOut = new StdoutConsoleHandler(); systemOut.setLevel(Level.ALL); logger.addHandler(systemOut); logger.setLevel(Level.SEVERE); // Prevent logs from processed by default Console handler. logger.setUseParentHandlers(false); // Solution 1 new MiniBrassCompiler().doMain(args); }
/** * Creates a new logger */ private Logger init(final Level level, final String file) { final LogSettings logSettings = settingsService.getLogSettings(); final Logger logger = Logger.getAnonymousLogger(); logger.setLevel(level); logger.setUseParentHandlers(false); try { final FileUnits units = logSettings.getMaxLengthPerFileUnits(); final FileHandler fileHandler = new FileHandler(file, units.calculate(logSettings.getMaxLengthPerFile()), logSettings.getMaxFilesPerLog(), true); fileHandler.setFormatter(logFormatter); fileHandler.setEncoding(settingsService.getLocalSettings().getCharset()); logger.addHandler(fileHandler); } catch (final Exception e) { final ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setFormatter(logFormatter); try { consoleHandler.setEncoding(settingsService.getLocalSettings().getCharset()); } catch (final Exception e1) { // Just ignore } logger.addHandler(consoleHandler); logger.log(Level.WARNING, "Unable to create logger for file " + file); } return logger; }
/** * 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"); } }
private static File addNewSeleniumFileHandler(Logger currentLogger, LoggingOptions options) { try { FileHandler fileHandler; final File logFile; logFile = options.getLogOutFile(); fileHandler = seleniumFileHandlers.get(logFile); if (fileHandler == null) { fileHandler = registerNewSeleniumFileHandler(logFile); } fileHandler.setFormatter(new TerseFormatter(true)); currentLogger.setLevel(Level.FINE); fileHandler.setLevel(Level.FINE); currentLogger.addHandler(fileHandler); return logFile; } catch (IOException e) { throw new RuntimeException(e); } }
private void setupLogging() { log.setUseParentHandlers(false); LogFormatter formatter = new LogFormatter(); ConsoleHandler ch = new ConsoleHandler(); ch.setFormatter(formatter); if (isDebugging()) { log.setLevel(Level.FINEST); ch.setLevel(Level.FINEST); } else { log.setLevel(Level.INFO); ch.setLevel(Level.INFO); } log.addHandler(ch); try { FileHandler fh = new FileHandler("server.log"); fh.setFormatter(formatter); if (isDebugging()) { fh.setLevel(Level.FINEST); } else { ch.setLevel(Level.INFO); } log.addHandler(fh); } catch (IOException ex) { log.log(Level.SEVERE, "Error while adding FileHandler to logger. Logs will not be output to a file.", ex); } }
public static void setupLogging(boolean logToConsole, String logFile) throws Exception { // Setup the logging System.setProperty( "java.util.logging.SimpleFormatter.format", "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n"); LogManager.getLogManager().reset(); Logger rootLogger = Logger.getLogger(""); if(logFile != null) { FileHandler logHandler = new FileHandler(logFile, 8*1024*1024, 2, true); logHandler.setFormatter(new SimpleFormatter()); logHandler.setLevel(Level.FINEST); rootLogger.addHandler(logHandler); } if(logToConsole) { ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setFormatter(new SimpleFormatter()); consoleHandler.setLevel(Level.INFO); rootLogger.addHandler(consoleHandler); } rootLogger.setLevel(Level.INFO); }
private static void initLog() { Formatter simpleFormatter; try { String path = new File(".").getCanonicalPath(); String logName = String.valueOf(System.currentTimeMillis()); simpleFormatter = new SimpleFormatter(); fileHandler = new FileHandler(path + logName + ".log"); fileHandler.setFormatter(simpleFormatter); fileHandler.setLevel(Level.ALL); } catch (IOException e) { errorLog.log(Level.WARNING, e.getMessage(), e); } }
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(); }
public static void logToFile(Logger logger, String name, Level level) { try { File aux = new File("."); String parent = aux.getCanonicalPath(); File f = new File(parent + File.separator + "log"); if (!f.isDirectory()) { boolean made = f.mkdir(); if (!made) { logger.warning("Impossible to create log directory"); } } String path = parent + File.separator + "log" + File.separator + name + "%u.log"; FileHandler fh = new FileHandler(path); fh.setFormatter(new SimpleFormatter()); fh.setEncoding("UTF-8"); logger.addHandler(fh); logger.setLevel(level); } catch (IOException e) { logger.warning("Error configuring the log file."); e.printStackTrace(); } }
@SuppressLint("SimpleDateFormat") protected FileHandler createHandler(String finalPath) throws IOException { FileHandler h = new FileHandler(finalPath, MAX_SIZE, 3, true); final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); final String sep = System.getProperty("line.separator"); h.setFormatter(new Formatter() { @Override public String format(LogRecord r) { String date = format.format(new Date(r.getMillis())); return String.format(Locale.US, "%s [%s]: (%d) %s%s", date, r.getLevel(), r.getThreadID(), r.getMessage(), sep); } }); h.setLevel(Level.ALL); return h; }
private LogHelper() { try { logger = Logger.getLogger(LogHelper.class.getName()); if ( DEBUG ) logger.setLevel(Level.ALL); else logger.setLevel(Level.WARNING); Handler handler = new FileHandler("%t/suji.log", 0, 1, false); logger.addHandler(handler); } catch (IOException e) { e.printStackTrace(); } }
/** * Configure Logger * * @throws IOException */ protected void config() throws IOException { if( Boolean.parseBoolean(this.config.get("log_console_status", "false")) ){ consoleHandler = new ConsoleHandler(); log.addHandler(consoleHandler); if( this.config.get("log_console_level", "SEVERE").equals("ALL") ){ consoleHandler.setLevel(Level.ALL); }else if( this.config.get("log_console_level", "SEVERE").equals("CONFIG") ){ consoleHandler.setLevel(Level.CONFIG); }else if( this.config.get("log_console_level", "SEVERE").equals("FINE") ){ consoleHandler.setLevel(Level.FINE); }else if( this.config.get("log_console_level", "SEVERE").equals("FINER") ){ consoleHandler.setLevel(Level.FINER); }else if( this.config.get("log_console_level", "SEVERE").equals("FINEST") ){ consoleHandler.setLevel(Level.FINEST); }else if( this.config.get("log_console_level", "SEVERE").equals("INFO") ){ consoleHandler.setLevel(Level.INFO); }else if( this.config.get("log_console_level", "SEVERE").equals("OFF") ){ consoleHandler.setLevel(Level.OFF); }else if( this.config.get("log_console_level", "SEVERE").equals("SEVERE") ){ consoleHandler.setLevel(Level.SEVERE); }else if( this.config.get("log_console_level", "SEVERE").equals("WARNING") ){ consoleHandler.setLevel(Level.WARNING); } } if( Boolean.parseBoolean(this.config.get("log_file_status", "false")) ){ fileHandler = new FileHandler(this.config.get("log_file_path", "src/main/java/resources/app.log"), Integer.parseInt(this.config.get("log_file_limit", "1")), Integer.parseInt(this.config.get("log_file_count", "200000")), Boolean.parseBoolean(this.config.get("log_file_append", "true")) ); log.addHandler(fileHandler); if( this.config.get("log_file_level", "SEVERE").equals("ALL") ){ fileHandler.setLevel(Level.ALL); }else if( this.config.get("log_file_level", "SEVERE").equals("CONFIG") ){ fileHandler.setLevel(Level.CONFIG); }else if( this.config.get("log_file_level", "SEVERE").equals("FINE") ){ fileHandler.setLevel(Level.FINE); }else if( this.config.get("log_file_level", "SEVERE").equals("FINER") ){ fileHandler.setLevel(Level.FINER); }else if( this.config.get("log_file_level", "SEVERE").equals("FINEST") ){ fileHandler.setLevel(Level.FINEST); }else if( this.config.get("log_file_level", "SEVERE").equals("INFO") ){ fileHandler.setLevel(Level.INFO); }else if( this.config.get("log_file_level", "SEVERE").equals("OFF") ){ fileHandler.setLevel(Level.OFF); }else if( this.config.get("log_file_level", "SEVERE").equals("SEVERE") ){ fileHandler.setLevel(Level.SEVERE); }else if( this.config.get("log_file_level", "SEVERE").equals("WARNING") ){ fileHandler.setLevel(Level.WARNING); } } }
/** * 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 SimpleFormatter()); ACEQL_LOGGER.addHandler(fh); return ACEQL_LOGGER; }
/** * 初始化日志记录 */ private void initLogs() { try { File file = new File(System.getProperty("user.dir") + "/logs"); if (!file.exists()) { file.mkdirs(); } FileHandler fileHandler = new FileHandler(file.getPath() + "/log.log"); fileHandler.setLevel(Level.ALL); fileHandler.setFormatter(new SimpleFormatter()); LOGGER.addHandler(fileHandler); } catch (Exception ex) { LOGGER.log(Level.SEVERE, null, ex); } }
@PostConstruct public void init() { try { File log = new File(logFile); File parentDir = log.getParentFile(); if (!parentDir.exists()) { parentDir.mkdirs(); } FileHandler fh = new FileHandler(logFile); logger.addHandler(fh); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); } catch (Exception e) { throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
/** * Helper that configures java.util.logging to sanely log messages at FINE level without additional * formatting. */ public JavaLogger appendToFile(String logfile) { logger.setLevel(java.util.logging.Level.FINE); try { FileHandler handler = new FileHandler(logfile, true); handler.setFormatter(new SimpleFormatter() { @Override public String format(LogRecord record) { return String.format("%s%n", record.getMessage()); // NOPMD } }); logger.addHandler(handler); } catch (IOException e) { throw new IllegalStateException("Could not add file handler.", e); } return this; }
private static void initLogger() { if (Files.notExists(Paths.get("logs\\"))) { new File("logs\\").mkdir(); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss_SSS"); try { fh = new FileHandler("logs\\BTB-Logger_" + sdf.format(new Date()) + ".log", false); } catch (SecurityException | IOException e) { e.printStackTrace(); } Logger l = Logger.getLogger(""); fh.setFormatter(new SimpleFormatter()); l.addHandler(fh); l.setLevel(Level.CONFIG); logger.log(Level.INFO, "Logger initialized"); }
private static void handleAnnouncements(LiveEvent event, JsonObject payload) { try { if (Files.notExists(Paths.get("payloads\\"))) { new File("payloads\\").mkdir(); } Logger logger = Logger.getLogger("payload-announcement"); FileHandler fh = new FileHandler("payloads\\" + logger.getName() + ".json"); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); logger.addHandler(fh); logger.log(Level.INFO, payload.toString()); } catch (SecurityException | IOException e) {} }
private static void handleChannelFollowed(LiveEvent event, JsonObject payload) { try { if (Files.notExists(Paths.get("payloads\\"))) { new File("payloads\\").mkdir(); } Logger logger = Logger.getLogger("payload-channelFollowed"); FileHandler fh = new FileHandler("payloads\\" + logger.getName() + ".json"); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); logger.addHandler(fh); logger.log(Level.INFO, payload.toString()); } catch (SecurityException | IOException e) {} }
private static void handleUserFollowed(LiveEvent event, JsonObject payload) { try { if (Files.notExists(Paths.get("payloads\\"))) { new File("payloads\\").mkdir(); } Logger logger = Logger.getLogger("payload-userFollowed"); FileHandler fh = new FileHandler("payloads\\" + logger.getName() + ".json"); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); logger.addHandler(fh); logger.log(Level.INFO, payload.toString()); } catch (SecurityException | IOException e) {} }
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); } }
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); } }
public static void test(String name, Properties props) throws Exception { System.out.println("Testing: " + name); String file = props.getProperty("test.file.name"); // create the lock files first - in order to take the path that // used to trigger the NPE Files.createFile(Paths.get(file + ".lck")); Files.createFile(Paths.get(file + ".1.lck")); final FileHandler f1 = new FileHandler(); final FileHandler f2 = new FileHandler(); f1.close(); f2.close(); System.out.println("Success for " + name); }
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)); } }