public void testUnknownLevels() throws IOException { TestLevel level = new TestLevel("WARN", 233); LogRecord r = new LogRecord(level, "Custom level test"); Formatter formatter = new LogFormatter(); String s = formatter.format(r); cleanKnownLevels(); final LogRecord[] rPtr = new LogRecord[] { null }; Handler h = new Handler() { @Override public void publish(LogRecord record) { rPtr[0] = record; } @Override public void flush() {} @Override public void close() throws SecurityException {} }; LogRecords.scan(new ReaderInputStream(new StringReader(s)), h); assertEquals("level", r.getLevel(), rPtr[0].getLevel()); }
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(); } }
/** * 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 setHandlers(Logger logger, File file) throws FileNotFoundException { for (Handler h : logger.getHandlers()) { logger.removeHandler(h); } Handler stderrHandler = new FlushedStreamHandler(System.err, noColors ? CommandLineLogFormatter.INSTANCE : CommandLineLogFormatter.COLORS); logger.addHandler(stderrHandler); if (file == null) stderrHandler.setLevel(logLevel); else { File dir = file.getParentFile(); if (dir != null) { dir.mkdirs(); } Handler fileHandler = new FlushedStreamHandler(new FileOutputStream(file, appendToLog), CommandLineLogFormatter.INSTANCE); logger.addHandler(fileHandler); if (logLevel.intValue() < Level.FINE.intValue()) { fileHandler.setLevel(logLevel); stderrHandler.setLevel(Level.FINE); } else { fileHandler.setLevel(Level.FINE); stderrHandler.setLevel(logLevel); } } }
static private void setLogging(int logging) { Level logLevel = getLogLevel(logging%10); Logger.getLogger("org.jboss.wfink.eap71.playground").setLevel(logLevel); logLevel = getLogLevel((logging/10)%10); Logger.getLogger("org.xnio").setLevel(logLevel); Logger.getLogger("org.jboss.remoting").setLevel(logLevel); //classes are remoting3 logLevel = getLogLevel((logging/100)%10); Logger.getLogger("org.jboss.ejb.client").setLevel(logLevel); logLevel = getLogLevel((logging/1000)%10); Logger.getLogger("org.wildfly").setLevel(logLevel); // Logger.getLogger("org.jboss.invocation").setLevel(logLevel); // change default ConsoleHandler Logger root = Logger.getLogger(""); Handler[] handlers = root.getHandlers(); for (int i = 0; i < handlers.length; i++) { root.removeHandler(handlers[i]); } ConsoleHandler handler = new ConsoleHandler(); handler.setFormatter(new PlaygroundFormatter()); handler.setLevel(Level.ALL); root.addHandler(handler); }
@BeforeClass public static void setUpBeforeClass() throws Exception { saveLog4j2Config = System.getProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); saveUserDir = System.getProperty("user.dir"); saveUserHome = System.getProperty("user.home"); julLogger = java.util.logging.Logger.getLogger(""); saveHandlers = julLogger.getHandlers(); for (Handler handler : saveHandlers) { julLogger.removeHandler(handler); } File log4j2XML = temporaryFolder_Config.newFile("log4j2.xml"); FileUtils.writeStringToFile(log4j2XML, "<Configuration/>", APPEND); System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, log4j2XML.toURI().toString()); }
public PlanBuilder(File planDir, File resourceDir) { super(); this.planDir = planDir; this.resourceDir = resourceDir; logger = Logger.getLogger(ALVISNLP_LOGGER_NAME); Level logLevel = Level.INFO; logger.setLevel(logLevel); logger.setUseParentHandlers(false); for (Handler h : logger.getHandlers()) { logger.removeHandler(h); } Handler stderrHandler = new FlushedStreamHandler(System.err, CommandLineLogFormatter.INSTANCE); logger.addHandler(stderrHandler); stderrHandler.setLevel(logLevel); moduleFactory = new CompoundCorpusModuleFactory(); moduleFactory.loadServiceFactories(CorpusModuleFactory.class, null, null, null); converterFactory = new CompoundParamConverterFactory(); converterFactory.loadServiceFactories(ParamConverterFactory.class, null, null, null); }
@AfterClass public static void tearDownAfterClass() throws Exception { for (Handler handler : saveHandlers) { julLogger.addHandler(handler); } if (saveLog4j2Config == null) { System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY); } else { System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, saveLog4j2Config); ((LoggerContext) LogManager.getContext(false)).reconfigure(); } if (saveUserDir == null) { System.clearProperty("user.dir"); } else { System.setProperty("user.dir", saveUserDir); } if (saveUserHome == null) { System.clearProperty("user.home"); } else { System.setProperty("user.home", saveUserHome); } }
private static synchronized Handler defaultHandler() { if (defaultHandler != null) return defaultHandler; File home = Places.getUserDirectory(); if (home != null && !CLIOptions.noLogging) { File dir = new File(new File(home, "var"), "log"); dir.mkdirs (); Handler h = NbLogging.createMessagesHandler(dir); defaultHandler = NbLogging.createDispatchHandler(h, 5000); } if (defaultHandler == null) { defaultHandler = streamHandler(); disabledConsole = true; } return defaultHandler; }
/** Allows tests to flush all standard handlers */ static void flush(boolean clear) { System.err.flush(); Handler s = streamHandler; if (s != null) { s.flush(); } Handler d = defaultHandler; if (d != null) { d.flush(); } if (clear) { streamHandler = null; defaultHandler = null; } }
private String readLog() throws IOException { Handler[] ha = Logger.getLogger("").getHandlers(); assertEquals("There is one handler", 1, ha.length); ha[0].flush(); assertTrue("Log file exists: " + log, log.canRead()); FileInputStream is = new FileInputStream(log); byte[] arr = new byte[(int)log.length()]; int r = is.read(arr); assertEquals("all read", arr.length, r); is.close(); return new String(arr); }
/** * Create a logging handler that sets value in an AtomicBoolean to true if * folder2 or text2.txt is refreshed. * * @param refreshedFlag The AtomicBoolean to be set to true if incorrect * refreshing was triggered. * @return The new logging handler. */ private Handler createHandler(final AtomicBoolean refreshedFlag) { Handler h = new Handler() { @Override public void publish(LogRecord record) { if (record.getMessage() != null && record.getMessage().startsWith("refreshImpl for ") && record.getParameters() != null && record.getParameters().length > 0 && (record.getParameters()[0] == folder2FO || record.getParameters()[0] == folder2text2TxtFO)) { refreshedFlag.set(true); } } @Override public void flush() { } @Override public void close() throws SecurityException { } }; return h; }
static void readLogs(Handler handler){ UIHandler.waitFlushed(); synchronized (UIGESTURE_LOG_LOCK) { File f = logFile(0); if (f == null || !f.exists()) { return ; } closeLogStream(); File f1 = logFile(1); if (logsSize < UIHandler.MAX_LOGS && f1 != null && f1.exists()) { scan(f1, handler); } scan(f, handler); } }
private static void scan(File f, Handler handler){ try { LogRecords.scan(f, handler); } catch (IOException ex) { LOG.log(Level.INFO, "Broken uilogs file, not all UI actions will be submitted", ex); if (!fileContentReported) { try { if (LOG.isLoggable(Level.INFO)) { LOG.log(Level.INFO, "Problematic file content = {0}", reportFileContent(f)); } } finally { fileContentReported = true; } } } }
MockConstrainedIndexer() { h = new Handler() { @Override public void publish(LogRecord record) { if (record.getMessage().equals("RootsWork-finished")) { sem.release(); } } @Override public void flush() { } @Override public void close() throws SecurityException { } }; final Logger log = Logger.getLogger(RepositoryUpdater.class.getName() + ".tests"); //NOI18N log.setLevel(Level.FINEST); log.addHandler(h); }
/** * Activates this feature. */ public static void activate() { try { Logger rootLogger = LogManager.getLogManager().getLogger(""); // remove old ConsoleHandler for( Handler handler : rootLogger.getHandlers() ) { rootLogger.removeHandler(handler); } activeHandler = new JDKLogHandler(); activeHandler.setLevel(Level.ALL); rootLogger.addHandler(activeHandler); rootLogger.setLevel(Level.ALL); } catch( Exception exc ) { LogFactory.getLog(TomcatLogRedirector.class).error("activation failed", exc); } }
public void setDebug(boolean debug) { _debug = debug; _consumerClient.setDebug(debug); if (!debug) { final Logger parentLogger = Logger.getAnonymousLogger().getParent(); // Disable console logger if debug mode not turned on for (Handler handler : parentLogger.getHandlers()) { if ( handler instanceof ConsoleHandler ) parentLogger.removeHandler(handler); } } }
public void testAlwaysSetParamters() throws Exception { String what = "actionDelegates.xml"; InputStream is = getClass().getResourceAsStream(what); class H extends Handler { int cnt; public void publish(LogRecord record) { cnt++; if (record.getParameters() == null) { fail("Each record shall have paramters, #" + cnt + " did not: " + record.getMessage()); } } public void flush() { } public void close() throws SecurityException { } } H h = new H(); is = getClass().getResourceAsStream(what); LogRecords.scan(is, h); is.close(); assertEquals("The four amount of records", 5, h.cnt); }
public static void main(String argv[]) { Locale.setDefault(Locale.US); // initialize j.u.l Looger: final Logger log = Logger.getLogger("sun.java2d.marlin"); log.addHandler(new Handler() { @Override public void publish(LogRecord record) { Throwable th = record.getThrown(); // detect any Throwable: if (th != null) { System.out.println("Test failed:\n" + record.getMessage()); th.printStackTrace(System.out); throw new RuntimeException("Test failed: ", th); } } @Override public void flush() { } @Override public void close() throws SecurityException { } }); // enable Marlin logging & internal checks: System.setProperty("sun.java2d.renderer.log", "true"); System.setProperty("sun.java2d.renderer.useLogger", "true"); System.setProperty("sun.java2d.renderer.doChecks", "true"); testFillDefaultAt(); testDrawComplexAt(); testPathClosed(); testStrokedShapes(); }
private int readAsSAX(final int[] cnts, int err, final File[] arr) throws IOException, FileNotFoundException { class H extends Handler { int cnt; public void publish(LogRecord record) { cnt++; } public void flush() { } public void close() throws SecurityException { } } int i = -1; for (File f : arr) { LOG.log(Level.WARNING, "scanning {0}", f.getPath()); i++; InputStream is = new BufferedInputStream(new FileInputStream(f)); H h = new H(); try { LogRecords.scan(is, h); } catch (IOException ex) { LOG.log(Level.WARNING, null, ex); err++; continue; } finally { is.close(); } assertEquals("The same amount for " + f, h.cnt, cnts[i]); } return err; }
public static void removeHandlers(Logger log) { if (log != null) { Handler[] handlers = log.getHandlers(); for (int i = 0; i < handlers.length; i++) { log.removeHandler(handlers[i]); } } }
public void testPurgeRemovedIgnoredFiles () throws Exception { File folder = new File(repositoryLocation, "folder"); final File file1 = new File(folder, "ignored"); folder.mkdirs(); file1.createNewFile(); File ignoreFile = new File(repositoryLocation, ".gitignore"); write(ignoreFile, "ignored"); getCache().refreshAllRoots(Collections.<File, Collection<File>>singletonMap(repositoryLocation, Collections.singleton(file1))); assertTrue(getCache().getStatus(file1).containsStatus(Status.NOTVERSIONED_EXCLUDED)); file1.delete(); assertFalse(file1.exists()); final boolean[] cleaned = new boolean[1]; Git.STATUS_LOG.addHandler(new Handler() { @Override public void publish(LogRecord record) { if (record.getMessage().contains("refreshAllRoots() uninteresting file: {0}") && file1.equals(record.getParameters()[0])) { cleaned[0] = true; } } @Override public void flush() { } @Override public void close() throws SecurityException { } }); getCache().refreshAllRoots(Collections.<File, Collection<File>>singletonMap(repositoryLocation, Collections.singleton(folder))); assertTrue(cleaned[0]); }
protected ComputedHints getHints(NbTestCase test, Rule hint, String relFilePath, FileObject fileObject, String caretLine) throws Exception { ComputedHints hints = computeHints(test, hint, relFilePath, fileObject, caretLine, ChangeOffsetType.NONE); if (checkAllHintOffsets()) { // Run alternate hint computation AFTER the real computation above since we will destroy the document... Logger.global.addHandler(new Handler() { @Override public void publish(LogRecord record) { if (record.getThrown() != null) { StringWriter sw = new StringWriter(); record.getThrown().printStackTrace(new PrintWriter(sw)); fail("Encountered error: " + sw.toString()); } } @Override public void flush() { } @Override public void close() throws SecurityException { } }); for (ChangeOffsetType type : new ChangeOffsetType[] { ChangeOffsetType.OUTSIDE, ChangeOffsetType.OVERLAP }) { computeHints(test, hint, relFilePath, fileObject, caretLine, type); } } return hints; }
/** Does its best to close provided handler. Can close handlers created by * {@link #createDispatchHandler(java.util.logging.Handler, int)} as well. */ public static void close(Handler h) { if (h == null) { return; } if (h instanceof DispatchingHandler) { ((DispatchingHandler)h).doClose(); } else { h.close(); } }
@Override public String getHead(Handler h) { StringBuilder sb = new StringBuilder(); sb.append("<?xml version=\"1.0\""); sb.append(" encoding='UTF-8'?>\n"); sb.append("<log>\n"); return sb.toString(); }
/** Logger for test purposes. */ static Handler createStreamHandler (PrintStream pw) { StreamHandler s = new StreamHandler ( pw, NbFormatter.FORMATTER ); return NbLogging.createDispatchHandler(s, 50); }
public static void setGlobalLevel(Level newLevel) { Logger rootLogger = LogManager.getLogManager().getLogger(""); rootLogger.setLevel(newLevel); for (Handler h : rootLogger.getHandlers()) { h.setLevel(newLevel); } }
public static void disableLogging() { // Disable Logging (FastSet sometimes complains about skewed key distributions with lots of WARNINGs) Logger root = Logger.getLogger(""); Handler[] handlers = root.getHandlers(); for (Handler handler : handlers) handler.setLevel(Level.OFF); }
private static Logger instantiateLogger(final String name, final Level level) { final Logger logger = java.util.logging.Logger.getLogger(name); AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { for (final Handler h : logger.getHandlers()) { logger.removeHandler(h); } logger.setLevel(level); logger.setUseParentHandlers(false); final Handler c = new ConsoleHandler(); c.setFormatter(new Formatter() { @Override public String format(final LogRecord record) { final StringBuilder sb = new StringBuilder(); sb.append('[') .append(record.getLoggerName()) .append("] ") .append(record.getMessage()) .append('\n'); return sb.toString(); } }); logger.addHandler(c); c.setLevel(level); return null; } }, createLoggerControlAccCtxt()); return logger; }
/** * Adds a PrintStreamLogHandler to the named logger, if there isn't one already. * This can be used repeatedly to acquire the same logger, but doing so would be * inefficient. Use Logger.getLogger after this has installed the handler. * * @param name Log name. * @param out Where to print the log. */ public static Logger getLogger(String name, PrintStream out) { Logger ret = Logger.getLogger(name); for (Handler handler : ret.getHandlers()) { if (handler instanceof PrintStreamLogHandler) { PrintStreamLogHandler pslh = (PrintStreamLogHandler) handler; if (pslh.getOut() == out) { return ret; } } } ret.addHandler(new PrintStreamLogHandler(name, out)); return ret; }
/** Obtiene, en formato XML, el registro acumulado de la ejecución actual. * @return Registro acumulado de la ejecución actual * @throws IOException Si no hay registro o este no se puede leer */ public static String getLogFile() throws IOException { if (!installed || logFile == null) { throw new IOException("No esta instalado el manejador de fichero"); //$NON-NLS-1$ } final Handler[] handlers = LOGGER.getHandlers(); for (final Handler h : handlers) { if (h instanceof FileHandler) { h.close(); LOGGER.info("Cerrado el manejador de fichero para permitir que sea procesado"); //$NON-NLS-1$ LOGGER.removeHandler(h); } } final InputStream is = new FileInputStream( new File( logFile.replace("%h", Platform.getUserHome()) //$NON-NLS-1$ ) ); final String log = new String(AOUtil.getDataFromInputStream(is)); is.close(); LOGGER.addHandler(createFileHandler(logFile)); return log; }
private static void setLevel(Logger pLogger, Level pLevel) { Handler[] handlers = pLogger.getHandlers(); for (Handler h : handlers) { h.setLevel(pLevel); } pLogger.setLevel(pLevel); }
public void testDeletedFileDoesNotReturnInputStream() throws Exception { final FileObject testFo = FileUtil.createData(root,"testfile.data"); final File testFile = FileUtil.toFile(testFo); final Logger LOGGER = Logger.getLogger(FileObj.class.getName()); final Handler handler = new Handler() { @Override public void publish(LogRecord record) { if ("FileObj.getInputStream_after_is_valid".equals(record.getMessage())) { testFile.delete(); } } @Override public void flush() { } @Override public void close() throws SecurityException { } }; final Level originalLevel = LOGGER.getLevel(); LOGGER.setLevel(Level.FINEST); try { LOGGER.addHandler(handler); try { testFo.getInputStream(); assertTrue("Exception not thrown by deleted file getInputStream()", false); } catch (FileNotFoundException e) { //pass - expected exception } finally { LOGGER.removeHandler(handler); } } finally { LOGGER.setLevel(originalLevel); } }
public void testHandlesThatImplementCallableForJButtonAreIncluded() throws Exception { class H extends Handler implements Callable<JButton> { public JButton button = new JButton("Extra"); public void publish(LogRecord arg0) { } public void flush() { } public void close() throws SecurityException { } public JButton call() throws Exception { return button; } } // end of H H handler = new H(); main.addHandler(handler); List<Object> options = Arrays.asList(NotifyExcPanel.computeOptions("prev", "next")); assertTrue("Contains our button: " + options, options.contains(handler.button)); }
@Test public void evaluateAnswer_evaluationBeforeAnswerProcessing() { // given Response response = mock(Response.class); Handler handler = mock(Handler.class); LOGGER.addHandler(handler); // when List<Boolean> evaluation = supplier.evaluateAnswer(response); // then assertThat(evaluation.isEmpty()).isTrue(); verify(handler).publish(any(LogRecord.class)); }
public Logger getLogger() throws IOException { Logger logger = Logger.getLogger("qsync"); logger.setUseParentHandlers(false); Handler handler = new FlushedStreamHandler(System.err, LogFormatter.INSTANCE); logger.addHandler(handler); if (logFile != null) { Handler fileHandler = new FileHandler(logFile); logger.addHandler(fileHandler); } return logger; }
public LoggerFinderAPITest(boolean verbose) { this.warnDuplicateMappings = verbose; for (Handler h : Logger.getLogger("").getHandlers()) { if (h instanceof ConsoleHandler) { Logger.getLogger("").removeHandler(h); } } Logger.getLogger("").addHandler( new Handler() { @Override public void publish(LogRecord record) { StringBuilder builder = new StringBuilder(); builder.append("GOT LogRecord: ") .append(record.getLevel().getLocalizedName()) .append(": [").append(record.getLoggerName()) .append("] ").append(record.getSourceClassName()) .append('.') .append(record.getSourceMethodName()).append(" -> ") .append(record.getMessage()) .append(' ') .append(record.getParameters() == null ? "" : Arrays.toString(record.getParameters())) ; System.out.println(builder); if (record.getThrown() != null) { record.getThrown().printStackTrace(System.out); } } @Override public void flush() {} @Override public void close() {} }); }
public void testCreateMessageIssue160019() throws IOException {//ignore annotations final List<LogRecord> logs = new ArrayList<LogRecord>(); ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream(); Exception rootExc = new NullPointerException("root"); Exceptions.attachMessage(rootExc, "annotation message"); LogRecord rec = new LogRecord(Level.SEVERE, "test"); rec.setThrown(rootExc); LogRecords.write(bos, rec); bos.close(); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); LogRecords.scan(bis, new Handler() { @Override public void publish(LogRecord record) { logs.add(record); } @Override public void flush() { } @Override public void close() throws SecurityException { } }); bis.close(); assertEquals(1, logs.size()); Throwable thrown = logs.get(0).getThrown(); assertEquals("thrown is annotated", "annotation message", thrown.getCause().getMessage()); String message = Installer.createMessage(thrown); assertEquals("annontation should be ignored", "NullPointerException: root", message); }
public void testRootLoggerHasHandler() throws Exception { for (Handler h : Logger.getLogger("").getHandlers()) { if (h instanceof Callable) { return; } } fail("No handler which implements Callable"); }
private void disable() { getProxy().getLogger().info("Disabling plugin " + getDescription().getName() + " version " + getDescription().getVersion() + " by " + getDescription().getAuthor()); try { onDisable(); for (Handler handler : getLogger().getHandlers()) handler.close(); } catch (Exception exception) { exception.printStackTrace(); } getProxy().getScheduler().cancel(this); getExecutorService().shutdownNow(); getProxy().getLogger().info("Disabled plugin " + getDescription().getName() + " version " + getDescription().getVersion() + " by " + getDescription().getAuthor()); }