Java Code Examples for java.util.logging.Handler#close()

The following examples show how to use java.util.logging.Handler#close() . 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: ExceptionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 2
Source File: Simulator.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 3
Source File: HeronInstance.java    From incubator-heron with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 4
Source File: SocketHandlerResourceDefinition.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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();
                        }
                    }
                }
            }
        }
    };
}
 
Example 5
Source File: LogFactory.java    From ns4_gear_watchdog with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化全局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;
}
 
Example 6
Source File: ExceptionTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 7
Source File: Timing.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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) {
        }
    }
}
 
Example 8
Source File: LogWrapper.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
  }
}
 
Example 9
Source File: BukkitPlugin.java    From ServerListPlus with GNU General Public License v3.0 5 votes vote down vote up
@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();
}
 
Example 10
Source File: ExceptionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 11
Source File: WildFlyLogContextSelector.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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);
            }
        }
    }
}
 
Example 12
Source File: ExceptionTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 13
Source File: NbLogging.java    From netbeans with Apache License 2.0 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 14
Source File: JavaUtilsLoggingBuildListener.java    From buck with Apache License 2.0 5 votes vote down vote up
public static void closeLogFile() {
  for (Handler handler : LOG.getHandlers()) {
    if (handler instanceof FileHandler) {
      LOG.removeHandler(handler);
      handler.close();
    }
  }
}
 
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: Process.java    From rapidminer-studio with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 17
Source File: LogHelper.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
public static void unregisterHandler(Handler handler) {
	if (handler == null) {
		return;
	}
	handler.close();
	Logger.getLogger("").removeHandler(handler);
}
 
Example 18
Source File: TopLogging.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void close() throws SecurityException {
    for (Handler h : instances) {
        h.close();
    }
}
 
Example 19
Source File: SIP2DESATransporter.java    From proarc with GNU General Public License v3.0 4 votes vote down vote up
private static void removeLogHandler(Handler handler) {
    Logger.getLogger("").removeHandler(handler);
    handler.close();
}
 
Example 20
Source File: MetricsManager.java    From incubator-heron with Apache License 2.0 4 votes vote down vote up
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);
  }
}