Java Code Examples for java.util.logging.Handler

The following are top voted examples for showing how to use java.util.logging.Handler. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: incubator-netbeans   File: LogFormatterTest.java   View source code 7 votes vote down vote up
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());
}
 
Example 2
Project: Equella   File: TomcatLogRedirector.java   View source code 7 votes vote down vote up
/**
 * 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);
	}
}
 
Example 3
Project: Suji   File: LogHelper.java   View source code 6 votes vote down vote up
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();
	}
}
 
Example 4
Project: aceql-http   File: DefaultDatabaseConfigurator.java   View source code 6 votes vote down vote up
/**
 * 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;

}
 
Example 5
Project: alvisnlp   File: AbstractAlvisNLP.java   View source code 6 votes vote down vote up
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);
          }
      }
  }
 
Example 6
Project: jboss-eap7.1-playground   File: AbstractLoggerMain.java   View source code 6 votes vote down vote up
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);
	}
 
Example 7
Project: monarch   File: GfshInitFileJUnitTest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 8
Project: alvisnlp   File: PlanBuilder.java   View source code 6 votes vote down vote up
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);
}
 
Example 9
Project: monarch   File: GfshInitFileJUnitTest.java   View source code 6 votes vote down vote up
@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);
  }
}
 
Example 10
Project: incubator-netbeans   File: TopLogging.java   View source code 6 votes vote down vote up
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;
}
 
Example 11
Project: incubator-netbeans   File: TopLogging.java   View source code 6 votes vote down vote up
/** 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;
    }
}
 
Example 12
Project: incubator-netbeans   File: TopLoggingOwnConfigClassTest.java   View source code 6 votes vote down vote up
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);
}
 
Example 13
Project: incubator-netbeans   File: LinuxNotifier235632Test.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 14
Project: incubator-netbeans   File: Installer.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 15
Project: incubator-netbeans   File: Installer.java   View source code 6 votes vote down vote up
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;
            }
        }
    }
}
 
Example 16
Project: incubator-netbeans   File: ConstrainedBinaryIndexerTest.java   View source code 6 votes vote down vote up
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);
}
 
Example 17
Project: Example.EMA.Java.SpeedGuide   File: SpeedGuideConsumer.java   View source code 6 votes vote down vote up
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);
		}
	}
}
 
Example 18
Project: incubator-netbeans   File: LogRecordsTest.java   View source code 5 votes vote down vote up
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);
}
 
Example 19
Project: openjdk-jdk10   File: CrashNaNTest.java   View source code 5 votes vote down vote up
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();
}
 
Example 20
Project: incubator-netbeans   File: ReadBigDataTest.java   View source code 5 votes vote down vote up
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;
}
 
Example 21
Project: incubator-netbeans   File: TestKit.java   View source code 5 votes vote down vote up
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]);
        }
    }
}
 
Example 22
Project: incubator-netbeans   File: StatusTest.java   View source code 5 votes vote down vote up
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]);
}
 
Example 23
Project: incubator-netbeans   File: StatusTest.java   View source code 5 votes vote down vote up
/**
 * It seems that cache.listFiles and cache.containsFiles called getStatus also on folders. Because folders are usually up-to-date (git does not track them),
 * this results in unnecessary call to getOwner, ignore logic or sharability.
 */
public void testSkipFoldersBug196702 () throws Exception {
    final File f1 = new File(repositoryLocation, "1");
    final File f2 = new File(f1, "2");
    final File f3 = new File(f2, "3");
    f3.mkdirs();
    File f = new File(f3, "f");
    f.createNewFile();
    
    FileStatusCache cache = getCache();
    cache.refreshAllRoots(Collections.<File, Collection<File>>singletonMap(repositoryLocation, Collections.singleton(f1)));
    Logger log = Logger.getLogger("org.netbeans.modules.git.status.cache");
    final boolean[] flags = new boolean[1];
    log.addHandler(new Handler() {
        @Override
        public void publish (LogRecord record) {
            if (record.getMessage().startsWith("getCachedStatus for file {0}:")) {
                if (Arrays.asList(f1, f2, f3).contains((File) record.getParameters()[0])) {
                    flags[0] = true;
                }
            }
        }

        @Override
        public void flush () { }

        @Override
        public void close () throws SecurityException { }
    });
    
    Collection<File> newFiles = Arrays.asList(cache.listFiles(new File[] { f1 }, EnumSet.of(FileInformation.Status.NEW_INDEX_WORKING_TREE)));
    assertEquals(Arrays.asList(f), newFiles);
    assertFalse(flags[0]);
    flags[0] = false;
    assertTrue(cache.containsFiles(Collections.singleton(f1), EnumSet.of(FileInformation.Status.NEW_INDEX_WORKING_TREE), true));
    assertFalse(flags[0]);
    assertFalse(cache.containsFiles(Collections.singleton(f1), EnumSet.of(FileInformation.Status.MODIFIED_INDEX_WORKING_TREE), true));
    assertFalse(flags[0]);
    
    // test we do not break anything with the bugfix: ignored files/folders should be recognized even without getStatus call
    SystemAction.get(IgnoreAction.class).performAction(VCSContext.forNodes(new Node[] { new AbstractNode(Children.LEAF, Lookups.fixed(f1)) }));
    flags[0] = false;
    Collection<File> ignoredFiles = Arrays.asList(cache.listFiles(new File[] { f1 }, EnumSet.of(FileInformation.Status.NOTVERSIONED_EXCLUDED)));
    assertEquals(Arrays.asList(f1), ignoredFiles);
    assertFalse(flags[0]);
    flags[0] = false;
    assertTrue(cache.containsFiles(Collections.singleton(f1), EnumSet.of(FileInformation.Status.NOTVERSIONED_EXCLUDED), true));
    assertFalse(flags[0]);
}
 
Example 24
Project: incubator-netbeans   File: CslTestBase.java   View source code 5 votes vote down vote up
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;
}
 
Example 25
Project: incubator-netbeans   File: NbLogging.java   View source code 5 votes vote down vote up
/** 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();
    }
}
 
Example 26
Project: incubator-netbeans   File: StartLog.java   View source code 5 votes vote down vote up
@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();
}
 
Example 27
Project: incubator-netbeans   File: TopLogging.java   View source code 5 votes vote down vote up
/** Logger for test purposes.
 */
static Handler createStreamHandler (PrintStream pw) {
    StreamHandler s = new StreamHandler (
        pw, NbFormatter.FORMATTER
    );
    return NbLogging.createDispatchHandler(s, 50);
}
 
Example 28
Project: Java-EX   File: LogUtil.java   View source code 5 votes vote down vote up
public static void setGlobalLevel(Level newLevel) {
  Logger rootLogger = LogManager.getLogManager().getLogger("");
  rootLogger.setLevel(newLevel);
  for (Handler h : rootLogger.getHandlers()) {
    h.setLevel(newLevel);
  }
}
 
Example 29
Project: metanome-algorithms   File: LoggingUtils.java   View source code 5 votes vote down vote up
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);
}
 
Example 30
Project: openjdk-jdk10   File: DebugLogger.java   View source code 5 votes vote down vote up
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;
}
 
Example 31
Project: alog   File: Alog.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 32
Project: mi-firma-android   File: LogManager.java   View source code 5 votes vote down vote up
/** Obtiene, en formato XML, el registro acumulado de la ejecuci&oacute;n actual.
 * @return Registro acumulado de la ejecuci&oacute;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;
}
 
Example 33
Project: openaudible   File: AudibleClient.java   View source code 5 votes vote down vote up
private static void setLevel(Logger pLogger, Level pLevel) {
    Handler[] handlers = pLogger.getHandlers();
    for (Handler h : handlers) {
        h.setLevel(pLevel);
    }
    pLogger.setLevel(pLevel);
}
 
Example 34
Project: incubator-netbeans   File: BaseFileObjectTestHid.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 35
Project: incubator-netbeans   File: NotifyExcPanelTest.java   View source code 5 votes vote down vote up
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));
}
 
Example 36
Project: empiria.player   File: AnswerEvaluationSupplierTest.java   View source code 5 votes vote down vote up
@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));

}
 
Example 37
Project: bibliome-java-utils   File: LogBuilder.java   View source code 5 votes vote down vote up
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;
}
 
Example 38
Project: openjdk-jdk10   File: LoggerFinderAPITest.java   View source code 5 votes vote down vote up
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() {}
    });
}
 
Example 39
Project: incubator-netbeans   File: InstallerTest.java   View source code 5 votes vote down vote up
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);
}
 
Example 40
Project: incubator-netbeans   File: BugTriggersTest.java   View source code 5 votes vote down vote up
public void testRootLoggerHasHandler() throws Exception {
    for (Handler h : Logger.getLogger("").getHandlers()) {
        if (h instanceof Callable) {
            return;
        }
    }
    fail("No handler which implements Callable");
}