public static void installCustomFormatter() { final boolean installCustomFormatter = Boolean.parseBoolean( OSystemVariableResolver.resolveSystemVariables( "${" + ENV_INSTALL_CUSTOM_FORMATTER + "}", "true")); if (!installCustomFormatter) return; try { // ASSURE TO HAVE THE ORIENT LOG FORMATTER TO THE CONSOLE EVEN IF NO CONFIGURATION FILE IS // TAKEN final Logger log = Logger.getLogger(""); if (log.getHandlers().length == 0) { // SET DEFAULT LOG FORMATTER final Handler h = new ConsoleHandler(); h.setFormatter(new OLogFormatter()); log.addHandler(h); } else { for (Handler h : log.getHandlers()) { if (h instanceof ConsoleHandler && !h.getFormatter().getClass().equals(OLogFormatter.class)) h.setFormatter(new OLogFormatter()); } } } catch (Exception e) { System.err.println( "Error while installing custom formatter. Logging could be disabled. Cause: " + e.toString()); } }
public static synchronized void createLoggers(boolean reinit) { if (m_initialized == true && reinit == false) { return; } if (!m_initialized) { Logger.getLogger("").removeHandler(Logger.getLogger("").getHandlers()[0]); } if (m_initialized) { m_severeLogger.removeHandler(m_severeLogger.getHandlers()[0]); m_nonSevereLogger.removeHandler(m_nonSevereLogger.getHandlers()[0]); } Handler severeHandler = new AMyConsoleHandler(System.err); severeHandler.setFormatter(new SingleLineFormatter()); m_severeLogger.addHandler(severeHandler); m_severeLogger.setLevel(getLoggingLevel()); Handler nonSevereHandler = new AMyConsoleHandler(System.out); nonSevereHandler.setFormatter(new SingleLineFormatter()); m_nonSevereLogger.addHandler(nonSevereHandler); m_nonSevereLogger.setLevel(getLoggingLevel()); m_initialized = true; }
/** * Set up a pair of Handlers for jOVAL system logging events, one logging to the specified logFile * and the other to the console, at the indicated logging level, and return a Logger configured to * use them. */ public static Logger createDuplex(File logFile, Level level) throws IOException { Handler logfileHandler = new FileHandler(logFile.getPath(), false); logfileHandler.setFormatter(new LogFormatter(Type.FILE)); logfileHandler.setLevel(level); Handler consoleHandler = new ConsoleHandler(); consoleHandler.setFormatter(new LogFormatter(Type.CONSOLE)); consoleHandler.setLevel(level); Logger logger = Logger.getLogger(JOVALMsg.getLogger().getName()); logger.setLevel(level); logger.addHandler(logfileHandler); logger.addHandler(consoleHandler); return logger; }
public void initialize() throws Exception { LogManager logManager = LogManager.getLogManager(); logManager.reset(); File logDir = new File(PlatformUtils.getWorkingDirectory() + File.separator + "Logs"); logDir.mkdirs(); Handler fileHandler = new FileHandler(new File(logDir, "spoutcraft_%g.log").getPath(), 100000, 5, true); fileHandler.setFormatter(new ClientLoggerFormatter()); Logger.getLogger("").addHandler(fileHandler); PrintStream stdout = System.out; /*PrintStream stderr = System.err;*/ Handler ConsoleHandle = new StreamHandler(stdout, new ClientLoggerFormatter()); Logger.getLogger("").addHandler(ConsoleHandle); /*Handler ErrHandle = new StreamHandler(stderr, new ClientLoggerFormatter()); Logger.getLogger("").addHandler(ErrHandle); */ Logger logger; SystemListenerStream los; logger = Logger.getLogger("stdout"); los = new SystemListenerStream(logger, SystemListenerLevel.STDOUT); System.setOut(new PrintStream(los, true)); /*logger = Logger.getLogger("stderr"); los= new SystemListenerStream(logger, SystemListenerLevel.STDERR); System.setErr(new PrintStream(los, true));*/ }
private UnexpectedErrorLogger() throws SecurityException, IOException { handler = new FileHandler("UnexpecterErrorLogger"); formatter = new SimpleFormatter(); handler.setFormatter(formatter); logger.addHandler(handler); }
private static void initLogger(Level loglevel) { logger.setLevel(loglevel); logger.setUseParentHandlers(false); Handler handler = new ConsoleHandler(); handler.setFormatter( new Formatter() { @Override public String format(LogRecord record) { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(record.getMillis()); StringBuilder out = new StringBuilder(); out.append( String.format( "[ %02d:%02d:%02d ] ", cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND))); out.append(record.getLevel().getName()).append(": ").append(record.getMessage()); if (logger.getLevel().intValue() <= Level.FINE.intValue()) { out.append(" [ ") .append(record.getSourceClassName()) .append(".") .append(record.getSourceMethodName()) .append("() ]"); } out.append(System.getProperty("line.separator")); return out.toString(); } }); logger.addHandler(handler); }
public static void main(String args[]) { try { Handler fh = new FileHandler("logging.txt"); fh.setFormatter(new SimpleFormatter()); java.util.logging.Logger.getLogger("de.javawi.stun").addHandler(fh); java.util.logging.Logger.getLogger("de.javawi.stun").setLevel(Level.ALL); BindingLifetimeTest test = new BindingLifetimeTest("jstun.javawi.de", 3478); // iphone-stun.freenet.de:3478 // larry.gloo.net:3478 // stun.xten.net:3478 test.test(); boolean continueWhile = true; while (continueWhile) { Thread.sleep(5000); if (test.getLifetime() != -1) { System.out.println( "Lifetime: " + test.getLifetime() + " Finished: " + test.isCompleted()); if (test.isCompleted()) continueWhile = false; } } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } }
static { Formatter formatter = new SingleLineFormatter(); Logger rootLogger = Logger.getLogger(""); for (Handler h : rootLogger.getHandlers()) { h.setFormatter(formatter); } }
public static void main(String[] args) { JmeFormatter formatter = new JmeFormatter(); Handler consoleHandler = new ConsoleHandler(); consoleHandler.setFormatter(formatter); Logger.getLogger("").removeHandler(Logger.getLogger("").getHandlers()[0]); Logger.getLogger("").addHandler(consoleHandler); createCanvas(appClass); try { Thread.sleep(500); } catch (InterruptedException ex) { } SwingUtilities.invokeLater( new Runnable() { public void run() { JPopupMenu.setDefaultLightWeightPopupEnabled(false); createFrame(); currentPanel.add(canvas, BorderLayout.CENTER); frame.pack(); startApp(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); }
public void startFile(String logfile) { File parent = new File(logfile).getParentFile(); if (!parent.isDirectory() && !parent.mkdirs()) { logger.warning("Could not create log folder: " + parent); } Handler fileHandler = new RotatingFileHandler(logfile); fileHandler.setFormatter(new DateOutputFormatter(FILE_DATE)); logger.addHandler(fileHandler); }
private Import() { try { Handler fh = new FileHandler("%h/jgnashimport%g.log"); fh.setFormatter(new SimpleFormatter()); logger.addHandler(fh); logger.setLevel(Level.FINE); } catch (IOException ioe) { logger.severe("Could not install file handler"); } }
@Override public Handler getHandler() { Handler handler = null; try { handler = new ConsoleHandler(); handler.setFormatter(new SimpleFormatter()); } catch (Exception e) { LoggerManager.DEFAULT_LOGGER.severe(ERROR_MESSAGE); } return handler; }
static { if ((System.getProperty("java.util.logging.config.file") == null) && (System.getProperty("java.util.logging.config.class") == null)) { LOGGER.setUseParentHandlers(false); final Handler handler = new ConsoleHandler(); handler.setFormatter(new PlainFormatter()); addOrSetHandler(handler); LOGGER.setLevel(Level.INFO); handler.setLevel(Level.ALL); } }
/** * Initialization of the task. * * @throws BuildException in case an error occured */ @Override public void init() throws BuildException { Logger baselogger = Logger.getLogger("org.cesta"); baselogger.setLevel(Level.ALL); // we want to disable other handlers and pass everything to Ant for (Handler h : baselogger.getHandlers()) baselogger.removeHandler(h); // create TaskLogHandler, which forwards all messages to Ant logging subsystem Handler handler = new TaskLogHandler(this); handler.setFormatter(new TaskLogFormatter()); handler.setLevel(Level.ALL); baselogger.addHandler(handler); }
void initialize() { // set this as a top level logger, to control console level logger = Logger.getLogger("com.jaivox.util.Log"); logger.setUseParentHandlers(false); Handler hConsole = new ConsoleHandler(); hConsole.setFormatter(new Logformat()); hConsole.setLevel(Level.FINEST); logger.addHandler(hConsole); logger.setLevel(Level.FINEST); // what is the level of this logger? String s = logger.getLevel().toString(); System.out.println("Logger log level after creating " + s); initialized = true; }
private static void configureLogging(CommandLineOptionHelper helper) { Level logLevel = helper.isParamPresent("-debug") ? Level.FINE : LoggingOptions.getDefaultLogLevel(); if (logLevel == null) { logLevel = Level.INFO; } Logger.getLogger("").setLevel(logLevel); Logger.getLogger("org.openqa.jetty").setLevel(Level.WARNING); String logFilename = helper.isParamPresent("-log") ? helper.getParamValue("-log") : LoggingOptions.getDefaultLogOutFile(); if (logFilename != null) { for (Handler handler : Logger.getLogger("").getHandlers()) { if (handler instanceof ConsoleHandler) { Logger.getLogger("").removeHandler(handler); } } try { Handler logFile = new FileHandler(new File(logFilename).getAbsolutePath(), true); logFile.setFormatter(new TerseFormatter(true)); logFile.setLevel(logLevel); Logger.getLogger("").addHandler(logFile); } catch (IOException e) { throw new RuntimeException(e); } } else { boolean logLongForm = helper.isParamPresent("-logLongForm"); for (Handler handler : Logger.getLogger("").getHandlers()) { if (handler instanceof ConsoleHandler) { handler.setLevel(logLevel); handler.setFormatter(new TerseFormatter(logLongForm)); } } } }
private Handler setupLogHandler(String fileName) { Handler handler; try { checkDirectory(logRoot); handler = new FileHandler( logRoot + System.getProperty("file.separator") + fileName + ".txt", 0, 1, true); handler.setFormatter(new SimpleFormatter()); } catch (IOException e) { throw new RuntimeException(e); } Logger.getLogger("").addHandler(handler); return handler; }
private static Logger createLogger() { Handler fh = null; try { fh = new FileHandler("logs/Disassembler.java.log"); } catch (IOException e) { e.printStackTrace(); System.exit(0); } Logger logger = Logger.getLogger(Disassembler.class.getName()); logger.setUseParentHandlers(false); SimpleFormatter formatter = new SimpleFormatter(); fh.setFormatter(formatter); logger.addHandler(fh); return logger; }
private static void initLogger() throws IOException { File logFolder = new File(BBCTMain.LOG_FOLDER_NAME); if (!logFolder.exists()) { logFolder.mkdir(); } // TODO: Configure logger using a property file. boolean append = true; Handler handler = new FileHandler(BBCTMain.LOG_FILE_NAME, append); handler.setFormatter(new SimpleFormatter()); Logger logger = Logger.getLogger(""); logger.setLevel(Level.INFO); logger.addHandler(handler); // TODO: Should I set this in a property file? System.setProperty("hsqldb.reconfig_logging", "false"); }
public static synchronized LocalOnlyAcsLogger getInstance(String namespace, Level level) { if (instance == null) { LogConfig testLogConfig = new LogConfig(); testLogConfig.setDefaultMinLogLevelLocal(AcsLogLevel.getNativeLevel(level).getAcsLevel()); instance = new LocalOnlyAcsLogger(namespace, testLogConfig); instance.setUseParentHandlers(false); Handler logHandler = new StdOutConsoleHandler(testLogConfig, namespace, null); logHandler.setFormatter( new AcsXMLLogFormatter() { public String format(LogRecord lr) { String xml = super.format(lr); return xml + '\n'; } }); logHandler.setLevel(level); instance.addHandler(logHandler); } return instance; }
public static void main(String[] args) { board = new Board(new State(100, 100), new State(400, 400)); logger = Logger.getLogger(main.class.getName()); finalCost = 0; try { handler = new FileHandler("logfile%g.txt"); handler.setFormatter(new SimpleFormatter()); logger.addHandler(handler); } catch (IOException Err) { System.out.println(Err.getMessage()); logger.log(Level.WARNING, "Error creating log file."); } try { board.setBoard("terrain.png"); logger.log(Level.INFO, "Loaded terrain image."); } catch (IOException NoFile) { logger.log(Level.SEVERE, "Error loading terrain image."); logger.log(Level.SEVERE, NoFile.getMessage()); return; } board.createOutImage(); logger.log(Level.INFO, "Starting."); finalCost = board.findPath(logger); if (finalCost == -1) { logger.log(Level.INFO, "No path found."); } else { logger.log(Level.INFO, "Cost was " + Integer.toString(finalCost)); } board.drawPath(); logger.log(Level.INFO, "Creating output image."); try { board.setOutImage("path.png"); } catch (IOException FileErr) { logger.log(Level.SEVERE, "Error creating path image."); } logger.log(Level.INFO, "Complete."); }
/** * A simple file logger which outputs only the message. * * @param fileName path to the output file * @return the logger */ private static Logger getFileLogger(String fileName) { // make sure parent directories exist new File(fileName).getParentFile().mkdirs(); final Logger logger = Logger.getLogger(fileName); try { logger.setUseParentHandlers(false); Handler handler = new FileHandler(fileName, true); handler.setFormatter( new Formatter() { @Override public String format(LogRecord record) { return record.getMessage() + "\n"; } }); logger.addHandler(handler); } catch (Exception e) { throw new RuntimeException(e); } return logger; }
/** * Utility main for importing a log into a BDB-JE environment or moving a database between * environments (2 arguments), or simply dumping a log to stderr in a more readable format (1 * argument). * * @param args command-line arguments * @throws DatabaseException * @throws IOException */ public static void main(String[] args) throws DatabaseException, IOException { Handler handler = new ConsoleHandler(); handler.setLevel(Level.ALL); handler.setFormatter(new OneLineSimpleLogger()); logger.addHandler(handler); logger.setUseParentHandlers(false); if (args.length == 2) { logger.setLevel(Level.INFO); populatePersistEnv(args[0], new File(args[1])); } else if (args.length == 1) { logger.setLevel(Level.FINE); populatePersistEnv(args[0], null); } else { System.out.println("Arguments: "); System.out.println(" source [target]"); System.out.println("...where source is either a txtser log file or BDB env dir"); System.out.println("and target, if present, is a BDB env dir. "); return; } }
private static void configureLogging() throws IOException { // We're no longer using LogManager and a logging.properties file to initialize // java.util.logging, because of // a limitation with Webstart limiting the use of handlers and formatters residing in the // system's classpath, // i.e. built-in ones. // // Read the java.util.logging configuration file bundled with the muCommander JAR, // replacing the JRE's // // logging.properties configuration. // InputStream resIn = // ResourceLoader.getRootPackageAsFile(Launcher.class).getChild("com/mucommander/logging.properties").getInputStream(); // LogManager.getLogManager().readConfiguration(resIn); // resIn.close(); // Remove default handlers Logger rootLogger = LogManager.getLogManager().getLogger(""); Handler handlers[] = rootLogger.getHandlers(); for (Handler handler : handlers) rootLogger.removeHandler(handler); // and add ours handlers = new Handler[] {new ConsoleHandler(), new DebugConsoleHandler()}; Formatter formatter = new SingleLineFormatter(); for (Handler handler : handlers) { handler.setFormatter(formatter); rootLogger.addHandler(handler); } // Set the log level to the value defined in the configuration updateLogLevel(getLogLevel()); // Logger fileLogger = FileLogger.getLogger(); // fileLogger.finest("fileLogger finest"); // fileLogger.finer("fileLogger finer"); // fileLogger.fine("fileLogger fine"); // fileLogger.config("fileLogger config"); // fileLogger.info("fileLogger info"); // fileLogger.warning("fileLogger warning"); // fileLogger.severe("fileLogger severe"); }
/** @throws IllegalArgumentException */ private static void createLoggerIfNotExists() throws IllegalArgumentException { // Nothing to do if already exists if (CLIENT_LOGGER != null) { return; } try { File logDir = new File(FrameworkFileUtil.getUserHomeDotKawansoftDir() + File.separator + "log"); logDir.mkdirs(); String logFilePattern = logDir.toString() + File.separator + "KawanfwClient.log"; CLIENT_LOGGER = Logger.getLogger("ClientLogger"); int limit = 50 * 1024 * 1024; Handler fh = new FileHandler(logFilePattern, limit, 4, true); fh.setFormatter(new SingleLineFormatterUtil(false)); CLIENT_LOGGER.addHandler(fh); } catch (Exception e) { throw new IllegalArgumentException("Impossible to create the CLIENT_LOGGER logger", e); } }
public static Logger initLogger() { Logger initlogger = Logger.getLogger(settings.getMainClass()); initlogger.setLevel(settings.getLogLevel()); boolean addconsole = false; if (settings.getLogToFile()) { try { Handler handler = new FileHandler(settings.getLogFile(), true); handler.setFormatter(new SimpleFormatter()); initlogger.addHandler(handler); } catch (Exception e) { Logger().warning("Could not set logfile " + settings.getLogFile() + ": " + e.getMessage()); addconsole = true; } } addconsole = settings.getLogToConsole() || addconsole; if (addconsole) { initlogger.addHandler(new ConsoleHandler()); } // restore original log state logger.setLevel(templevel); templevel = null; return initlogger; }
public static void main(String[] args) throws Exception { Security.addProvider(new BouncyCastleProvider()); // add logger.setUseParentHandlers(false); Handler ch = new ConsoleHandler(); ch.setFormatter(new TextFormatter()); logger.addHandler(ch); if (args == null || (args.length != 1 && args.length != 2 && args.length != 5 && args.length != 6)) { usage(); return; } InetSocketAddress listen; try { int port = Integer.parseInt(args[0]); listen = new InetSocketAddress("localhost", port); } catch (NumberFormatException nfe) { usage(); return; } String proxy = "DIRECT"; if (args.length == 2 || args.length == 6) { proxy = args[1]; } DataSource dataSource = null; if (args.length == 5) { dataSource = createDataSource(args[1], args[2], args[3], args[4]); } else if (args.length == 6) { dataSource = createDataSource(args[2], args[3], args[4], args[5]); } final ProxySelector ps = getProxySelector(proxy); DefaultHttpRequestHandler drh = new DefaultHttpRequestHandler() { @Override protected HttpClient createClient() { HttpClient client = super.createClient(); client.setProxySelector(ps); client.setSoTimeout(90000); return client; } }; ServerGroup sg = new ServerGroup(); sg.addServer(listen); drh.setServerGroup(sg); HttpRequestHandler rh = drh; rh = new LoggingHttpRequestHandler(rh); if (dataSource != null) { JdbcMessageDAO dao = new JdbcMessageDAO(); dao.setDataSource(dataSource); dao.createTables(); rh = new RecordingHttpRequestHandler(dao, rh, 1024 * 1024); rh = new ConversationServiceHttpRequestHandler("127.0.0.2", dao, rh); } BufferedMessageInterceptor bmi = new BufferedMessageInterceptor() { @Override public Action directResponse(RequestHeader request, MutableResponseHeader response) { // System.err.println(new String(request.getHeader()) // + "+++++++++++\n" + new String(response.getHeader()) // + "==========="); return Action.BUFFER; } @Override public Action directRequest(MutableRequestHeader request) { // System.err.println(new String(request.getHeader()) // + "==========="); return Action.BUFFER; } }; rh = new BufferingHttpRequestHandler(rh, bmi, 1024 * 1024); HttpProxyConnectionHandler hpch = new HttpProxyConnectionHandler(rh); SSLContextSelector cp = getSSLContextSelector(); TargetedConnectionHandler tch = new SSLConnectionHandler(cp, true, hpch); tch = new LoopAvoidingTargetedConnectionHandler(sg, tch); hpch.setConnectHandler(tch); TargetedConnectionHandler socks = new SocksConnectionHandler(tch, true); Proxy p = new Proxy(listen, socks, null); p.setSocketTimeout(90000); p.start(); System.out.println("Listener started on " + listen); System.out.println("Press Enter to terminate"); new BufferedReader(new InputStreamReader(System.in)).readLine(); p.stop(); System.out.println("Terminated"); System.exit(0); }
private static void setGLogFormatter(Logger logger) { for (Handler h : logger.getHandlers()) { h.setFormatter(new LogFormatter()); } }
protected Util(String[] args) { CommandLineParser cmdLineParse = new PosixParser(); Options options = new Options(); options.addOption("h", "help", false, "show this help message and exit"); options.addOption( OptionBuilder.withLongOpt("host") .withDescription("host to connect to (default 0.0.0.0)") .hasArg(true) .withArgName("HOST") .create('H')); options.addOption( OptionBuilder.withLongOpt("username") .withDescription("username to use for authentication") .hasArg(true) .withArgName("USERNAME") .create('u')); options.addOption( OptionBuilder.withLongOpt("password") .withDescription("password to use for authentication") .hasArg(true) .withArgName("PASSWORD") .create('w')); options.addOption( OptionBuilder.withLongOpt("port") .withDescription("port to connect to (default 5672)") .hasArg(true) .withArgName("PORT") .create('p')); options.addOption( OptionBuilder.withLongOpt("frame-size") .withDescription("specify the maximum frame size") .hasArg(true) .withArgName("FRAME_SIZE") .create('f')); options.addOption( OptionBuilder.withLongOpt("container-name") .withDescription("Container name") .hasArg(true) .withArgName("CONTAINER_NAME") .create('C')); options.addOption(OptionBuilder.withLongOpt("ssl").withDescription("Use SSL").create('S')); options.addOption( OptionBuilder.withLongOpt("remote-hostname") .withDescription("hostname to supply in the open frame") .hasArg(true) .withArgName("HOST") .create('O')); if (hasBlockOption()) options.addOption( OptionBuilder.withLongOpt("block") .withDescription("block until messages arrive") .create('b')); if (hasCountOption()) options.addOption( OptionBuilder.withLongOpt("count") .withDescription("number of messages to send (default 1)") .hasArg(true) .withArgName("COUNT") .create('c')); if (hasModeOption()) options.addOption( OptionBuilder.withLongOpt("acknowledge-mode") .withDescription( "acknowledgement mode: AMO|ALO|EO (At Least Once, At Most Once, Exactly Once") .hasArg(true) .withArgName("MODE") .create('k')); if (hasSubjectOption()) options.addOption( OptionBuilder.withLongOpt("subject") .withDescription("subject message property") .hasArg(true) .withArgName("SUBJECT") .create('s')); if (hasSingleLinkPerConnectionMode()) options.addOption( OptionBuilder.withLongOpt("single-link-per-connection") .withDescription( "acknowledgement mode: AMO|ALO|EO (At Least Once, At Most Once, Exactly Once") .hasArg(false) .create('Z')); if (hasFilterOption()) options.addOption( OptionBuilder.withLongOpt("filter") .withDescription("filter, e.g. exact-subject=hello; matching-subject=%.a.#") .hasArg(true) .withArgName("<TYPE>=<VALUE>") .create('F')); if (hasTxnOption()) { options.addOption("x", "txn", false, "use transactions"); options.addOption( OptionBuilder.withLongOpt("batch-size") .withDescription("transaction batch size (default: 1)") .hasArg(true) .withArgName("BATCH-SIZE") .create('B')); options.addOption( OptionBuilder.withLongOpt("rollback-ratio") .withDescription("rollback ratio - must be between 0 and 1 (default: 0)") .hasArg(true) .withArgName("RATIO") .create('R')); } if (hasLinkDurableOption()) { options.addOption("d", "durable-link", false, "use a durable link"); } if (hasStdInOption()) options.addOption("i", "stdin", false, "read messages from stdin (one message per line)"); options.addOption( OptionBuilder.withLongOpt("trace") .withDescription("trace logging specified categories: RAW, FRM") .hasArg(true) .withArgName("TRACE") .create('t')); if (hasSizeOption()) options.addOption( OptionBuilder.withLongOpt("message-size") .withDescription("size to pad outgoing messages to") .hasArg(true) .withArgName("SIZE") .create('z')); if (hasResponseQueueOption()) options.addOption( OptionBuilder.withLongOpt("response-queue") .withDescription("response queue to reply to") .hasArg(true) .withArgName("RESPONSE_QUEUE") .create('r')); if (hasLinkNameOption()) { options.addOption( OptionBuilder.withLongOpt("link") .withDescription("link name") .hasArg(true) .withArgName("LINK") .create('l')); } if (hasWindowSizeOption()) { options.addOption( OptionBuilder.withLongOpt("window-size") .withDescription("credit window size") .hasArg(true) .withArgName("WINDOW-SIZE") .create('W')); } CommandLine cmdLine = null; try { cmdLine = cmdLineParse.parse(options, args); } catch (ParseException e) { printUsage(options); System.exit(-1); } if (cmdLine.hasOption('h') || cmdLine.getArgList().isEmpty()) { printUsage(options); System.exit(0); } _host = cmdLine.getOptionValue('H', "0.0.0.0"); _remoteHost = cmdLine.getOptionValue('O', null); String portStr = cmdLine.getOptionValue('p', "5672"); String countStr = cmdLine.getOptionValue('c', "1"); _useSSL = cmdLine.hasOption('S'); if (hasWindowSizeOption()) { String windowSizeStr = cmdLine.getOptionValue('W', "100"); _windowSize = Integer.parseInt(windowSizeStr); } if (hasSubjectOption()) { _subject = cmdLine.getOptionValue('s'); } if (cmdLine.hasOption('u')) { _username = cmdLine.getOptionValue('u'); } if (cmdLine.hasOption('w')) { _password = cmdLine.getOptionValue('w'); } if (cmdLine.hasOption('F')) { _filter = cmdLine.getOptionValue('F'); } _port = Integer.parseInt(portStr); _containerName = cmdLine.getOptionValue('C'); if (hasBlockOption()) _block = cmdLine.hasOption('b'); if (hasLinkNameOption()) _linkName = cmdLine.getOptionValue('l'); if (hasLinkDurableOption()) _durableLink = cmdLine.hasOption('d'); if (hasCountOption()) _count = Integer.parseInt(countStr); if (hasStdInOption()) _useStdIn = cmdLine.hasOption('i'); if (hasSingleLinkPerConnectionMode()) _useMultipleConnections = cmdLine.hasOption('Z'); if (hasTxnOption()) { _useTran = cmdLine.hasOption('x'); _batchSize = Integer.parseInt(cmdLine.getOptionValue('B', "1")); _rollbackRatio = Double.parseDouble(cmdLine.getOptionValue('R', "0")); } if (hasModeOption()) { _mode = AcknowledgeMode.ALO; if (cmdLine.hasOption('k')) { _mode = AcknowledgeMode.valueOf(cmdLine.getOptionValue('k')); } } if (hasResponseQueueOption()) { _responseQueue = cmdLine.getOptionValue('r'); } _frameSize = Integer.parseInt(cmdLine.getOptionValue('f', "65536")); if (hasSizeOption()) { _messageSize = Integer.parseInt(cmdLine.getOptionValue('z', "-1")); } String categoriesList = cmdLine.getOptionValue('t'); String[] categories = categoriesList == null ? new String[0] : categoriesList.split("[, ]"); for (String cat : categories) { if (cat.equalsIgnoreCase("FRM")) { FRAME_LOGGER.setLevel(Level.FINE); Formatter formatter = new Formatter() { @Override public String format(final LogRecord record) { return "[" + record.getMillis() + " FRM]\t" + record.getMessage() + "\n"; } }; for (Handler handler : FRAME_LOGGER.getHandlers()) { FRAME_LOGGER.removeHandler(handler); } Handler handler = new ConsoleHandler(); handler.setLevel(Level.FINE); handler.setFormatter(formatter); FRAME_LOGGER.addHandler(handler); } else if (cat.equalsIgnoreCase("RAW")) { RAW_LOGGER.setLevel(Level.FINE); Formatter formatter = new Formatter() { @Override public String format(final LogRecord record) { return "[" + record.getMillis() + " RAW]\t" + record.getMessage() + "\n"; } }; for (Handler handler : RAW_LOGGER.getHandlers()) { RAW_LOGGER.removeHandler(handler); } Handler handler = new ConsoleHandler(); handler.setLevel(Level.FINE); handler.setFormatter(formatter); RAW_LOGGER.addHandler(handler); } } _args = cmdLine.getArgs(); }
public static void main(String[] args) { log = Logger.getLogger(Main.class.getName()); try { // Setting up logging Logger packageLog = Logger.getLogger(ChatBot.class.getPackage().getName()); File logFile = new File(LOGFILE + ".log"); if (logFile.exists()) { Calendar cal = Calendar.getInstance(); File backup = new File( String.format( "%s_%d_%d_%d.log", LOGFILE, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH))); if (backup.exists()) try (BufferedReader reader = new BufferedReader(new FileReader(logFile)); PrintWriter writer = new PrintWriter(new FileWriter(backup, true))) { char buff[] = new char[1024]; int n; while ((n = reader.read(buff)) > 0) { writer.write(buff, 0, n); } log.info("Appened log to backup " + backup.getName()); } catch (IOException e) { log.log(Level.SEVERE, "Couldn't append log to " + backup.getName(), e); } else { try { FileUtils.moveFile(logFile, backup); log.info("Moved log to backup " + backup.getName()); } catch (IOException e) { log.log(Level.SEVERE, "Couldn't move log to " + backup.getName(), e); } } } //noinspection ResultOfMethodCallIgnored // logFile.delete(); Handler handler = new FileHandler(LOGFILE + ".log"); handler.setFormatter(new SimpleFormatter()); packageLog.setLevel(Level.FINE); packageLog.addHandler(handler); // Starting up XMPPCraft Main main = new Main(); PipeInputStream stdinPipe = new PipeInputStream(1048576); PipeOutputStream stdoutPipe = new PipeOutputStream(); main.init( System.in, new PipeOutputStream(stdinPipe), new PipeInputStream(stdoutPipe, 1048576)); System.setIn(stdinPipe); System.setOut(new PrintStream(new TeeOutputStream(System.out, stdoutPipe))); main.start(); // Starting up Minecraft MinecraftServer.main(args); // DummyMinecraftServer.main(args); } catch (KeyManagementException | NoSuchAlgorithmException | SmackException | XMPPException | IOException e) { String filename = String.format( "crashreport_%s_%s.log", e.getClass().getSimpleName(), new SimpleDateFormat("MM_dd.HH_mm").format(new Date())); File f = new File(filename); try { if (f.createNewFile()) { PrintWriter out = new PrintWriter(f); out.println("Error on startup :"); out.printf( "JVM: %s %s on %s\n", System.getProperty("java.vm.name"), System.getProperty("java.runtime.version"), System.getProperty("os.name")); e.printStackTrace(out); out.flush(); out.close(); } } catch (IOException ignore) { } // lol what can you do log.severe("Crash detected. Generating report."); } }