java.util.logging.Handler# close ( ) 源码实例Demo

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

源代码1 项目: ns4_gear_watchdog   文件: LogFactory.java

/**
 * 初始化全局Logger
 *
 * @return
 */
private static void initGlobalLog(String logPath) {
    // 获取Log
    Logger log = Logger.getLogger(LOG_NAME);
    // 为log设置全局等级
    log.setLevel(Level.ALL);
    Handler[] hs = log.getHandlers();
    for (Handler h : hs) {
        h.close();
        log.removeHandler(h);
    }
    // 添加控制台handler
    //LogUtil.addConsoleHandler(log, Level.INFO);
    // 添加文件输出handler
    LogUtil.addFileHandler(log, Level.INFO, logPath);
    // 设置不适用父类的handlers,这样不会在控制台重复输出信息
    log.setUseParentHandlers(false);
    globalLog = log;
}
 
源代码2 项目: quarkus   文件: Timing.java

public static void printStopTime(String name) {
    final long stopTimeNanoSeconds = System.nanoTime() - bootStopTime;
    final Logger logger = Logger.getLogger("io.quarkus");
    final BigDecimal secondsRepresentation = convertToBigDecimalSeconds(stopTimeNanoSeconds);
    logger.infof("%s stopped in %ss",
            (UNSET_VALUE.equals(name) || name == null || name.trim().isEmpty()) ? "Quarkus" : name,
            secondsRepresentation);
    bootStopTime = -1;

    /**
     * We can safely close log handlers after stop time has been printed.
     */
    Handler[] handlers = InitialConfigurator.DELAYED_HANDLER.clearHandlers();
    for (Handler handler : handlers) {
        try {
            handler.close();
        } catch (Throwable ignored) {
        }
    }
}
 
源代码3 项目: netbeans   文件: ExceptionTest.java

/**
 * Test PayaraException with message throwing and logging.
 */
@Test
public void testPayaraExceptionWithMsg() {
    String gfieMsg = "Test exception";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        throw new PayaraIdeException(gfieMsg);
    } catch (PayaraIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int contains = logMsg.indexOf(gfieMsg);
    assertTrue(contains > -1);
}
 
源代码4 项目: netbeans   文件: ExceptionTest.java

/**
 * Test GlassFishException with message throwing and logging.
 */
@Test
public void testGlassFishExceptionWithMsg() {
    String gfieMsg = "Test exception";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        throw new GlassFishIdeException(gfieMsg);
    } catch (GlassFishIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int contains = logMsg.indexOf(gfieMsg);
    assertTrue(contains > -1);
}
 

@Override
protected OperationStepHandler additionalModelStep(final LogContextConfiguration logContextConfiguration) {
    return new OperationStepHandler() {
        @Override
        public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
            // If we don't require runtime steps to be executed we need to discard records on the delayed handler
            if (!requiresRuntime(context)) {
                HandlerConfiguration configuration = logContextConfiguration.getHandlerConfiguration(context.getCurrentAddressValue());
                if (configuration != null) {
                    if (!(configuration.getInstance() instanceof DelayedHandler)) {
                        throw LoggingLogger.ROOT_LOGGER.invalidType(DelayedHandler.class, configuration.getInstance().getClass());
                    }
                    final DelayedHandler delayedHandler = (DelayedHandler) configuration.getInstance();
                    // Clear any previous handlers and close them, then add the new handler
                    final Handler[] current = delayedHandler.setHandlers(new Handler[] {new DiscardingHandler()});
                    if (current != null) {
                        for (Handler handler : current) {
                            handler.close();
                        }
                    }
                }
            }
        }
    };
}
 
源代码6 项目: incubator-heron   文件: HeronInstance.java

public void stop() {
  synchronized (this) {
    LOG.severe("Instance Process exiting.\n");
    for (Handler handler : java.util.logging.Logger.getLogger("").getHandlers()) {
      handler.close();
    }

    // Attempts to shutdown all the thread in threadsPool. This will send Interrupt to every
    // thread in the pool. Threads may implement a clean Interrupt logic.
    threadsPool.shutdownNow();

    // TODO : It is not clear if this signal should be sent to all the threads (including threads
    // not owned by HeronInstance). To be safe, not sending these interrupts.
    Runtime.getRuntime().halt(1);
  }
}
 
源代码7 项目: incubator-heron   文件: Simulator.java

private void handleException(Thread thread, Throwable exception) {
  LOG.severe("Local Mode Process exiting.");
  LOG.log(Level.SEVERE,
      "Exception caught in thread: " + thread.getName() + " with id: " + thread.getId(),
      exception);
  for (Handler handler : java.util.logging.Logger.getLogger("").getHandlers()) {
    handler.close();
  }

  // Attempts to shutdown all the thread in threadsPool. This will send Interrupt to every
  // thread in the pool. Threads may implement a clean Interrupt logic.
  threadsPool.shutdownNow();

  // not owned by HeronInstance). To be safe, not sending these interrupts.
  Runtime.getRuntime().halt(1);
}
 
源代码8 项目: lemminx   文件: LogHelper.java

public static void unregisterHandler(Handler handler) {
	if (handler == null) {
		return;
	}
	handler.close();
	Logger.getLogger("").removeHandler(handler);
}
 
源代码9 项目: netbeans   文件: NbLogging.java

/** 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();
    }
}
 
源代码10 项目: ServerListPlus   文件: BukkitPlugin.java

@Override
public void onDisable() {
    try {
        core.stop();
    } catch (ServerListPlusException ignored) {}
    getLogger().info(getDisplayName() + " disabled.");
    // BungeeCord closes the log handlers automatically, but Bukkit does not
    for (Handler handler : getLogger().getHandlers())
        handler.close();
}
 
源代码11 项目: gemfirexd-oss   文件: LogWrapper.java

/**
 * Removed all the handlers of the given {@link Logger} instance.
 *
 * @param logger {@link Logger} to be cleaned up.
 */
private static void cleanupLogger(Logger logger) {
  if (logger != null) {
    Handler[] handlers = logger.getHandlers();
    for (Handler handler : handlers) {
      handler.close();
      logger.removeHandler(handler);
    }
  }
}
 
源代码12 项目: netbeans   文件: ExceptionTest.java

/**
 * Test PayaraException with message and cause <code>Throwable</code>
 * throwing and logging.
 */
@Test
public void testPayaraExceptionWithMsgAndCause() {
    String gfieMsg = "Test exception";
    String causeMsg = "Cause exception";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        try {
            throw new Exception(causeMsg);
        } catch (Exception e) {
            throw new PayaraIdeException(gfieMsg, e);
        }
    } catch (PayaraIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int containsGfieMsg = logMsg.indexOf(gfieMsg);
    int containsCauseMsg = logMsg.indexOf(causeMsg);
    assertTrue(containsGfieMsg > -1 && containsCauseMsg > -1);
}
 

private static void clearLogContext() {
    // Remove the configurator and clear the log context
    final Configurator configurator = EMBEDDED_LOG_CONTEXT.getLogger("").detach(Configurator.ATTACHMENT_KEY);
    // If this was a PropertyConfigurator we can use the LogContextConfiguration API to tear down the LogContext
    if (configurator instanceof PropertyConfigurator) {
        final LogContextConfiguration logContextConfiguration = ((PropertyConfigurator) configurator).getLogContextConfiguration();
        clearLogContext(logContextConfiguration);
    } else if (configurator instanceof LogContextConfiguration) {
        clearLogContext((LogContextConfiguration) configurator);
    } else {
        // Remove all the handlers and close them as well as reset the loggers
        final List<String> loggerNames = Collections.list(EMBEDDED_LOG_CONTEXT.getLoggerNames());
        for (String name : loggerNames) {
            final Logger logger = EMBEDDED_LOG_CONTEXT.getLoggerIfExists(name);
            if (logger != null) {
                final Handler[] handlers = logger.clearHandlers();
                if (handlers != null) {
                    for (Handler handler : handlers) {
                        handler.close();
                    }
                }
                logger.setFilter(null);
                logger.setUseParentFilters(false);
                logger.setUseParentHandlers(true);
                logger.setLevel(Level.INFO);
            }
        }
    }
}
 
源代码14 项目: netbeans   文件: ExceptionTest.java

/**
 * Test GlassFishException with message and cause <code>Throwable</code>
 * throwing and logging.
 */
@Test
public void testGlassFishExceptionWithMsgAndCause() {
    String gfieMsg = "Test exception";
    String causeMsg = "Cause exception";
    java.util.logging.Logger logger = Logger.getLogger();
    Level logLevel = logger.getLevel();
    OutputStream logOut = new ByteArrayOutputStream(256);
    Handler handler = new StreamHandler(logOut, new SimpleFormatter());
    handler.setLevel(Level.WARNING);
    logger.addHandler(handler);       
    logger.setLevel(Level.WARNING);
    try {
        try {
            throw new Exception(causeMsg);
        } catch (Exception e) {
            throw new GlassFishIdeException(gfieMsg, e);
        }
    } catch (GlassFishIdeException gfie) {
        handler.flush();
    } finally {
        logger.removeHandler(handler);
        handler.close();
        logger.setLevel(logLevel);
    }
    String logMsg = logOut.toString();
    int containsGfieMsg = logMsg.indexOf(gfieMsg);
    int containsCauseMsg = logMsg.indexOf(causeMsg);
    assertTrue(containsGfieMsg > -1 && containsCauseMsg > -1);
}
 

public static void closeLogFile() {
  for (Handler handler : LOG.getHandlers()) {
    if (handler instanceof FileHandler) {
      LOG.removeHandler(handler);
      handler.close();
    }
  }
}
 
源代码16 项目: 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
      }
    }
  }
}
 
源代码17 项目: rapidminer-studio   文件: Process.java

/**
 * Finishes the process and cleans up everything, including GUI.
 *
 * @since 7.4
 */
private void finishProcess(Handler logHandler) {
	stop();
	tearDown();
	if (logHandler != null) {
		getLogger().removeHandler(logHandler);
		logHandler.close();
	}
	ActionStatisticsCollector.getInstance().logExecutionFinished(this);
}
 
源代码18 项目: netbeans   文件: TopLogging.java

@Override
public void close() throws SecurityException {
    for (Handler h : instances) {
        h.close();
    }
}
 
源代码19 项目: proarc   文件: SIP2DESATransporter.java

private static void removeLogHandler(Handler handler) {
    Logger.getLogger("").removeHandler(handler);
    handler.close();
}
 
源代码20 项目: incubator-heron   文件: MetricsManager.java

private void handleException(Thread thread, Throwable exception) {
  // We would fail fast when errors occur
  if (exception instanceof Error) {
    LOG.log(Level.SEVERE,
        "Error caught in thread: " + thread.getName()
            + " with thread id: " + thread.getId() + ". Process halting...",
        exception);
    Runtime.getRuntime().halt(1);
  }

  // We would fail fast when exceptions happen in main thread
  if (thread.getId() == mainThreadId) {
    LOG.log(Level.SEVERE,
        "Exception caught in main thread. Process halting...",
        exception);
    Runtime.getRuntime().halt(1);
  }

  LOG.log(Level.SEVERE,
      "Exception caught in thread: " + thread.getName()
          + " with thread id: " + thread.getId(),
      exception);

  String sinkId = null;
  Integer thisSinkRetryAttempts = 0;

  // We enforced the name of thread running particular IMetricsSink equal to its sink-id
  // If the thread name is a key of SinkExecutors, then it is a thread running IMetricsSink
  if (sinkExecutors.containsKey(thread.getName())) {
    sinkId = thread.getName();
    // Remove the unneeded Communicator bind with Metrics Manager Server
    metricsManagerServer.removeSinkCommunicator(sinkId);

    // Remove the old sink executor and close the sink
    SinkExecutor oldSinkExecutor = sinkExecutors.remove(sinkId);
    SysUtils.closeIgnoringExceptions(oldSinkExecutor);

    thisSinkRetryAttempts = sinksRetryAttempts.remove(sinkId);
  }

  if (sinkId != null && thisSinkRetryAttempts != 0) {
    LOG.info(String.format("Restarting IMetricsSink: %s with %d available retries",
        sinkId, thisSinkRetryAttempts));

    // That means it was a sinkExecutor throwing exceptions and threadName is sinkId
    SinkExecutor newSinkExecutor = initSinkExecutor(sinkId);

    // Update the SinkExecutor in sinkExecutors
    sinkExecutors.put(sinkId, newSinkExecutor);

    // Update the retry attempts if it is > 0
    if (thisSinkRetryAttempts > 0) {
      thisSinkRetryAttempts--;
    }
    sinksRetryAttempts.put(sinkId, thisSinkRetryAttempts);

    // Update the list of Communicator in Metrics Manager Server
    metricsManagerServer.addSinkCommunicator(sinkId, newSinkExecutor.getCommunicator());

    // Restart it
    executors.execute(newSinkExecutor);
  } else if (sinkId != null
      && thisSinkRetryAttempts == 0
      && sinkExecutors.size() > 0) {
    // If the dead executor is the only one executor and it is removed,
    // e.g. sinkExecutors.size() == 0, we would exit the process directly

    LOG.severe("Failed to recover from exceptions for IMetricsSink: " + sinkId);
    LOG.info(sinkId + " would close and keep running rest sinks: " + sinkExecutors.keySet());
  } else {
    // It is not recoverable (retried too many times, or not an exception from IMetricsSink)
    // So we would do basic cleaning and exit
    LOG.info("Failed to recover from exceptions; Metrics Manager Exiting");
    for (Handler handler : java.util.logging.Logger.getLogger("").getHandlers()) {
      handler.close();
    }
    // Attempts to shutdown all the thread in threadsPool. This will send Interrupt to every
    // thread in the pool. Threads may implement a clean Interrupt logic.
    executors.shutdownNow();

    // (including threads not owned by HeronInstance). To be safe, not sending these
    // interrupts.
    Runtime.getRuntime().halt(1);
  }
}