下面列出了java.util.logging.Handler# close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 初始化全局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;
}
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) {
}
}
}
/**
* 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);
}
/**
* 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();
}
}
}
}
}
};
}
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);
}
}
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);
}
public static void unregisterHandler(Handler handler) {
if (handler == null) {
return;
}
handler.close();
Logger.getLogger("").removeHandler(handler);
}
/** 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();
}
}
@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();
}
/**
* 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);
}
}
}
/**
* 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);
}
}
}
}
/**
* 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();
}
}
}
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
}
}
}
}
/**
* 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);
}
@Override
public void close() throws SecurityException {
for (Handler h : instances) {
h.close();
}
}
private static void removeLogHandler(Handler handler) {
Logger.getLogger("").removeHandler(handler);
handler.close();
}
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);
}
}