getHandlers ( )源码实例Demo

java.util.logging.Logger#getHandlers ( )源码实例Demo

下面列出了java.util.logging.Logger#getHandlers ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: styx   文件: LOGBackConfigurer.java
/**
 * Initialize LOGBack from the given URL.
 *
 * @param url              the url pointing to the location of the config file.
 * @param installJULBridge set to true to install SLF4J JUL bridge
 * @throws IllegalArgumentException if the url points to a non existing location or an error occurs during the parsing operation.
 */
public static void initLogging(URL url, boolean installJULBridge) {
    StaticLoggerBinder.getSingleton();
    ContextSelector selector = ContextSelectorStaticBinder.getSingleton().getContextSelector();
    LoggerContext loggerContext = selector.getLoggerContext();
    loggerContext.stop();
    ContextInitializer ctxi = new ContextInitializer(loggerContext);
    try {
        ctxi.configureByResource(url);
        loggerContext.start();
        if (installJULBridge) {
            //uninstall already present handlers we want to
            //continue logging through SLF4J after this point
            Logger l = LogManager.getLogManager().getLogger("");
            for (Handler h : l.getHandlers()) {
                l.removeHandler(h);
            }
            SLF4JBridgeHandler.install();

        }
    } catch (JoranException e) {
        throw new IllegalArgumentException("exception while initializing LOGBack", e);
    }
}
 
源代码2 项目: cloudsync   文件: Cloudsync.java
public Cloudsync(final String[] args)
{
	this.options = new CmdOptions(args);

	final Logger logger = Logger.getLogger("cloudsync");
	logger.setLevel(Level.ALL);

	java.util.logging.Handler[] handlers = logger.getHandlers();
	for(java.util.logging.Handler h : handlers) {
		h.close();
		logger.removeHandler(h);
	}
	final ConsoleHandler handler = new LogconsoleHandler();
	handler.setLevel(Level.ALL);
	logger.addHandler(handler);
	logger.setUseParentHandlers(false);
}
 
源代码3 项目: fastods   文件: FastOdsTest.java
@Test
public final void testOpenFileError() throws IOException {
    // let's hide logging infos
    final Logger rootLogger = Logger.getLogger("");
    rootLogger.setLevel(Level.OFF);
    for (final Handler h : rootLogger.getHandlers()) {
        h.setLevel(Level.OFF);
    }

    final File f = new File(".", "pom.xml");
    FastOds.desktop = PowerMock.createMock(Desktop.class);

    PowerMock.resetAll();
    FastOds.desktop.open(f);
    EasyMock.expectLastCall().andThrow(new IOException());

    PowerMock.replayAll();
    Assert.assertFalse(FastOds.openFile(f));

    PowerMock.verifyAll();
}
 
源代码4 项目: Sentinel   文件: BaseJulLogger.java
/**
 * Remove all current handlers from the logger and attach it with the given log handler.
 *
 * @param logger  logger
 * @param handler the log handler
 */
static void disableOtherHandlers(Logger logger, Handler handler) {
    if (logger == null) {
        return;
    }

    synchronized (logger) {
        Handler[] handlers = logger.getHandlers();
        if (handlers == null) {
            return;
        }
        if (handlers.length == 1 && handlers[0].equals(handler)) {
            return;
        }

        logger.setUseParentHandlers(false);
        // Remove all current handlers.
        for (Handler h : handlers) {
            logger.removeHandler(h);
        }
        // Attach the given handler.
        logger.addHandler(handler);
    }
}
 
源代码5 项目: twister2   文件: LoggingHelper.java
public static void initTwisterFileLogHandler(String logFile,
                                             String logDir,
                                             Config config) throws IOException {
  Logger rootLogger = Logger.getLogger("");

  boolean foundAndInit = false;
  for (Handler handler : rootLogger.getHandlers()) {
    if (handler instanceof Twister2FileLogHandler) {
      ((Twister2FileLogHandler) handler).init(logDir, logFile, config);
      foundAndInit = true;
    }
  }
  if (!foundAndInit) {
    Twister2FileLogHandler twister2FileLogHandler = new Twister2FileLogHandler();
    twister2FileLogHandler.init(logDir, logFile, config);
    LoggingHelper.addLoggingHandler(twister2FileLogHandler);
  }
}
 
源代码6 项目: buck   文件: LogConfig.java
public static void flushLogs() {
  Logger rootLogger = LogManager.getLogManager().getLogger("");
  if (rootLogger == null) {
    return;
  }
  Handler[] handlers = rootLogger.getHandlers();
  if (handlers == null) {
    return;
  }
  for (Handler h : handlers) {
    h.flush();
  }
}
 
源代码7 项目: openjdk-jdk9   文件: TestInferCaller.java
public static void main(String[] args) {
    TestInferCaller test = new TestInferCaller();
    Logger root = Logger.getLogger("");
    for (Handler h : root.getHandlers()) {
        h.setLevel(Level.OFF);
    }
    root.addHandler(new TestHandler());

    for (Logger logger : Arrays.asList(root, Logger.getGlobal(),
            Logger.getAnonymousLogger(), Logger.getLogger("foo.bar"))) {
        System.out.println("Testing with: " + loggerName(logger) + " " + logger.getClass());
        test.test(logger);
    }
}
 
源代码8 项目: selenium   文件: WebDriverServlet.java
private synchronized Logger configureLogging() {
  Logger logger = Logger.getGlobal();
  logger.addHandler(LoggingHandler.getInstance());

  Logger rootLogger = Logger.getLogger("");
  boolean sessionLoggerAttached = false;
  for (Handler handler : rootLogger.getHandlers()) {
    sessionLoggerAttached |= handler instanceof PerSessionLogHandler;
  }
  if (!sessionLoggerAttached) {
    rootLogger.addHandler(LoggingManager.perSessionLogHandler());
  }

  return logger;
}
 
源代码9 项目: twister2   文件: LoggingHelper.java
public static void setLogLevel(Level level) {
  Logger rootLogger = Logger.getLogger("");
  for (Handler handler : rootLogger.getHandlers()) {
    handler.setLevel(level);
  }

  rootLogger.setLevel(level);
}
 
源代码10 项目: phoebus   文件: FormulaTest.java
@BeforeClass
public static void setup()
{
    System.setProperty("java.util.logging.ConsoleHandler.formatter",
                       "java.util.logging.SimpleFormatter");
    // 1: date, 2: source, 3: logger, 4: level, 5: message, 6:thrown
    System.setProperty("java.util.logging.SimpleFormatter.format",
                       "%1$tH:%1$tM:%1$tS %4$s %5$s%6$s%n");

    final Logger logger = Logger.getLogger("");
    logger.setLevel(Level.FINE);
    for (Handler handler : logger.getHandlers())
        handler.setLevel(logger.getLevel());
}
 
源代码11 项目: gemfirexd-oss   文件: ClientSharedUtils.java
private static void clearLogger() {
  final Logger log = logger;
  if (log != null) {
    logger = DEFAULT_LOGGER;
    for (Handler h : log.getHandlers()) {
      log.removeHandler(h);
      // try and close the handler ignoring any exceptions
      try {
        h.close();
      } catch (Exception ex) {
        // ignore
      }
    }
  }
}
 
源代码12 项目: nashorn   文件: Logging.java
private static Logger instantiateLogger(final String name, final Level level) {
    final Logger logger = java.util.logging.Logger.getLogger(name);
    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 logger;
}
 
源代码13 项目: phoebus   文件: ArrayMonitorDemo.java
public static void main(String[] args) throws Exception
{
    // Configure logging
    LogManager.getLogManager().readConfiguration(PVASettings.class.getResourceAsStream("/pva_logging.properties"));
    final Logger root = Logger.getLogger("");
    // Profiler shows blocking in ConsoleHandler,
    // so reduce log messages to only warnings for performance tests
    root.setLevel(Level.WARNING);
    for (Handler handler : root.getHandlers())
        handler.setLevel(root.getLevel());

    // Start PVA servers
    ForkJoinPool.commonPool().submit(() -> serve("demo1", TimeUnit.MILLISECONDS, 10));
    ForkJoinPool.commonPool().submit(() -> serve("demo2", TimeUnit.MILLISECONDS, 10));
    ForkJoinPool.commonPool().submit(() -> serve("demo3", TimeUnit.MILLISECONDS, 10));

    // PVA Client
    final PVAClient pva = new PVAClient();
    final PVAChannel ch1 = pva.getChannel("demo1");
    final PVAChannel ch2 = pva.getChannel("demo2");
    final PVAChannel ch3 = pva.getChannel("demo3");
    CompletableFuture.allOf(ch1.connect(), ch2.connect(), ch3.connect()).get();

    final MonitorListener listener = (ch, changes, overruns, data) ->
    {
        // System.out.println(ch.getName() + " = " + data.get("value") + " " + overruns);
        PVADoubleArray array = data.get("value");
        System.out.println(ch.getName() + " = " + array.get().length + " " + overruns);
    };
    ch1.subscribe("", listener );
    ch2.subscribe("", listener);
    ch3.subscribe("", listener);

    synchronized (ArrayMonitorDemo.class)
    {
        ArrayMonitorDemo.class.wait();
    }
}
 
源代码14 项目: netbeans   文件: TopLogging.java
/** Initializes the logging configuration. Invoked by <code>LogManager.readConfiguration</code> method.
 */
public TopLogging() {
    AWTHandler.install();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Properties properties = System.getProperties();
    configureFromProperties(os, properties);
    try {
        StartLog.unregister();
        LogManager.getLogManager().readConfiguration(new ByteArrayInputStream(os.toByteArray()));
    } catch (IOException ex) {
        ex.printStackTrace(OLD_ERR);
    } finally {
        StartLog.register();
    }


    Logger logger = Logger.getLogger (""); // NOI18N

    Handler[] old = logger.getHandlers();
    for (int i = 0; i < old.length; i++) {
        logger.removeHandler(old[i]);
    }
    logger.addHandler(defaultHandler ());
    if (!disabledConsole) { // NOI18N
        logger.addHandler (streamHandler ());
    }
    logger.addHandler(new LookupDel());
}
 
源代码15 项目: gcp-token-broker   文件: BrokerServer.java
private static void setLoggingLevel() {
    Level level = Level.parse(AppSettings.getInstance().getString(AppSettings.LOGGING_LEVEL));
    Logger root = Logger.getLogger("");
    root.setLevel(level);
    for (Handler handler : root.getHandlers()) {
        handler.setLevel(level);
    }
}
 
源代码16 项目: birt   文件: LogConfigurationTest.java
private void clearHandlers( Logger logger )
{
    Handler[] handlers = logger.getHandlers();
    for ( int i = 0; i < handlers.length; i += 1 )
    {
        logger.removeHandler( handlers[i] );
    }
}
 
源代码17 项目: phoebus   文件: TestHelper.java
public static void setupLogging()
{
    System.setProperty("java.util.logging.SimpleFormatter.format",
            "%1$tH:%1$tM:%1$tS %2$s %4$s: %5$s%6$s%n");

    Logger logger = Logger.getLogger("");
    logger.setLevel(Level.FINE);
    for (Handler handler : logger.getHandlers())
        handler.setLevel(Level.FINE);

    logger = Logger.getLogger("org.csstudio.vtype.pv");
    logger.setLevel(Level.WARNING);
    logger = Logger.getLogger("com.cosylab.epics.caj");
    logger.setLevel(Level.WARNING);
}
 
源代码18 项目: gemfirexd-oss   文件: LogService.java
private static void clearHandler(Logger root) {
  for (Handler handler : root.getHandlers()) {
    root.removeHandler(handler);
    try {
      handler.close();
    } catch (Exception e) {
    }
  }
}
 
源代码19 项目: phoebus   文件: ConnectDemo.java
public static void main(String[] args) throws Exception
{
    // Configure logging
    LogManager.getLogManager().readConfiguration(PVASettings.class.getResourceAsStream("/pva_logging.properties"));
    final Logger root = Logger.getLogger("");
    root.setLevel(Level.CONFIG);
    for (Handler handler : root.getHandlers())
        handler.setLevel(root.getLevel());

    // Start PVA server
    ForkJoinPool.commonPool().submit(() -> serve("demo1", TimeUnit.SECONDS, 1));

    // PVA Client
    final PVAClient pva = new PVAClient();
    while (true)
    {
        System.err.println("\nCREATE CHANNEL ----------------------------");
        final PVAChannel ch = pva.getChannel("demo1");
        ch.connect().get();
        System.err.println("READ --------------------------------------");
        final PVAStructure data = ch.read("").get();
        System.err.println(ch.getName() + " = " + data.get("value"));
        System.err.println("CLOSE -------------------------------------\n");
        ch.close();
        // TimeUnit.SECONDS.sleep(1);
    }
}
 
源代码20 项目: Open-Lowcode   文件: Module.java
/**
 * This allows to launch from command line the generation of an application
 * 
 * @param args an aray of strings with one element indicating the full path of
 *             the main module of the application (e.g.
 *             com.mycompany.myapp.Mymodule )
 */
public static void main(String args[]) {
	long starttime = new Date().getTime();
	ConsoleHandler handler = new ConsoleHandler();
	handler.setFormatter(new ConsoleFormatter());
	handler.setLevel(Level.INFO);
	Logger mainlogger = Logger.getLogger("");
	for (int i = 0; i < mainlogger.getHandlers().length; i++) {
		mainlogger.removeHandler(mainlogger.getHandlers()[i]);
	}
	mainlogger.addHandler(handler);

	if (args.length == 0) {
		logger.severe("Error : syntax java org.openlowcode.design.module.Module class1 [class2] ...");
		logger.severe(
				"where class1, class2 and following  are the full class (with path) of the main module of your application");
		System.exit(1);
	}
	String[] classpathlist = args;
	ArrayList<String> successfullmodules = new ArrayList<String>();
	ArrayList<String> errormodules = new ArrayList<String>();
	for (int i = 0; i < classpathlist.length; i++) {
		String classpath = classpathlist[i];
		try {
			logger.info("will try to launch generation for class = " + classpath);
			Class<?> moduleclass = Class.forName(classpath);
			logger.info("Class generated");

			Object module = moduleclass.newInstance();
			logger.info("Object generated");

			Module castedmodule = (Module) module;
			castedmodule.finalizemodel();
			castedmodule.generateSources();
			successfullmodules.add(classpath);
		} catch (Throwable e) {
			errormodules.add(classpath + " - " + e.getMessage() + "\n    - " + e.getStackTrace()[0] + "\n    - "
					+ (e.getStackTrace().length > 1 ? e.getStackTrace()[1] : ""));
			logger.severe("Exception " + e.getMessage());
			for (int s = 0; s < e.getStackTrace().length; s++) {
				logger.severe(" - " + e.getStackTrace()[s].toString());
			}

		}
	}
	long endtime = new Date().getTime();
	long executioninsec = (endtime - starttime) / 1000;
	System.err.println(" *** Generation Report *** " + args.length + " modules in " + executioninsec + "s");
	for (int i = 0; i < successfullmodules.size(); i++)
		System.err.println(" SUCCESS " + successfullmodules.get(i));
	for (int i = 0; i < errormodules.size(); i++)
		System.err.println(" ERROR " + errormodules.get(i));
}