Java Code Examples for java.util.logging.Logger#getHandlers()

The following examples show how to use java.util.logging.Logger#getHandlers() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoggingHelper.java    From twister2 with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 2
Source File: BaseJulLogger.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 3
Source File: FastOdsTest.java    From fastods with GNU General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example 4
Source File: Cloudsync.java    From cloudsync with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example 5
Source File: LOGBackConfigurer.java    From styx with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Source File: BrokerServer.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 7
Source File: ConnectDemo.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
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);
    }
}
 
Example 8
Source File: LogService.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private static void clearHandler(Logger root) {
  for (Handler handler : root.getHandlers()) {
    root.removeHandler(handler);
    try {
      handler.close();
    } catch (Exception e) {
    }
  }
}
 
Example 9
Source File: TestHelper.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
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);
}
 
Example 10
Source File: LogConfigurationTest.java    From birt with Eclipse Public License 1.0 5 votes vote down vote up
private void clearHandlers( Logger logger )
{
    Handler[] handlers = logger.getHandlers();
    for ( int i = 0; i < handlers.length; i += 1 )
    {
        logger.removeHandler( handlers[i] );
    }
}
 
Example 11
Source File: LogConfig.java    From buck with Apache License 2.0 5 votes vote down vote up
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();
  }
}
 
Example 12
Source File: TopLogging.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** 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());
}
 
Example 13
Source File: ArrayMonitorDemo.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
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();
    }
}
 
Example 14
Source File: Logging.java    From nashorn with GNU General Public License v2.0 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);
    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;
}
 
Example 15
Source File: ClientSharedUtils.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
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
      }
    }
  }
}
 
Example 16
Source File: FormulaTest.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
@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());
}
 
Example 17
Source File: LoggingHelper.java    From twister2 with Apache License 2.0 5 votes vote down vote up
public static void setLogLevel(Level level) {
  Logger rootLogger = Logger.getLogger("");
  for (Handler handler : rootLogger.getHandlers()) {
    handler.setLevel(level);
  }

  rootLogger.setLevel(level);
}
 
Example 18
Source File: WebDriverServlet.java    From selenium with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 19
Source File: TestInferCaller.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 20
Source File: Module.java    From Open-Lowcode with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * 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));
}