下面列出了怎么用java.util.logging.ErrorManager的API类实例代码及写法,或者点击链接到github查看源代码。
protected void closeWriter() {
writerLock.writeLock().lock();
try {
if (writer == null) {
return;
}
writer.write(getFormatter().getTail(this));
writer.flush();
writer.close();
writer = null;
date = "";
} catch (Exception e) {
reportError(null, e, ErrorManager.CLOSE_FAILURE);
} finally {
writerLock.writeLock().unlock();
}
}
/**
* Flush the writer.
*/
@Override
public void flush() {
writerLock.readLock().lock();
try {
if (writer == null) {
return;
}
writer.flush();
} catch (Exception e) {
reportError(null, e, ErrorManager.FLUSH_FAILURE);
} finally {
writerLock.readLock().unlock();
}
}
private void clean() {
if (maxDays <= 0) {
return;
}
DELETE_FILES_SERVICE.submit(new Runnable() {
@Override
public void run() {
try (DirectoryStream<Path> files = streamFilesForDelete()) {
for (Path file : files) {
Files.delete(file);
}
} catch (IOException e) {
reportError("Unable to delete log files older than [" + maxDays + "] days",
null, ErrorManager.GENERIC_FAILURE);
}
}
});
}
private static Map<String, Handler> createNamedHandlers(LogConfig config,
List<RuntimeValue<Optional<Formatter>>> possibleFormatters, ErrorManager errorManager,
List<LogCleanupFilterElement> filterElements) {
Map<String, Handler> namedHandlers = new HashMap<>();
for (Entry<String, ConsoleConfig> consoleConfigEntry : config.consoleHandlers.entrySet()) {
final Handler consoleHandler = configureConsoleHandler(consoleConfigEntry.getValue(), errorManager, filterElements,
possibleFormatters, null);
addToNamedHandlers(namedHandlers, consoleHandler, consoleConfigEntry.getKey());
}
for (Entry<String, FileConfig> fileConfigEntry : config.fileHandlers.entrySet()) {
final Handler fileHandler = configureFileHandler(fileConfigEntry.getValue(), errorManager, filterElements);
addToNamedHandlers(namedHandlers, fileHandler, fileConfigEntry.getKey());
}
for (Entry<String, SyslogConfig> sysLogConfigEntry : config.syslogHandlers.entrySet()) {
final Handler syslogHandler = configureSyslogHandler(sysLogConfigEntry.getValue(), errorManager, filterElements);
if (syslogHandler != null) {
addToNamedHandlers(namedHandlers, syslogHandler, sysLogConfigEntry.getKey());
}
}
return namedHandlers;
}
protected void closeWriter() {
writerLock.writeLock().lock();
try {
if (writer == null)
return;
writer.write(getFormatter().getTail(this));
writer.flush();
writer.close();
writer = null;
date = "";
} catch (Exception e) {
reportError(null, e, ErrorManager.CLOSE_FAILURE);
} finally {
writerLock.writeLock().unlock();
}
}
/**
* Flush the writer.
*/
@Override
public void flush() {
writerLock.readLock().lock();
try {
if (writer == null)
return;
writer.flush();
} catch (Exception e) {
reportError(null, e, ErrorManager.FLUSH_FAILURE);
} finally {
writerLock.readLock().unlock();
}
}
protected void closeWriter() {
writerLock.writeLock().lock();
try {
if (writer == null)
return;
writer.write(getFormatter().getTail(this));
writer.flush();
writer.close();
writer = null;
date = "";
} catch (Exception e) {
reportError(null, e, ErrorManager.CLOSE_FAILURE);
} finally {
writerLock.writeLock().unlock();
}
}
/**
* Flush the writer.
*/
@Override
public void flush() {
writerLock.readLock().lock();
try {
if (writer == null)
return;
writer.flush();
} catch (Exception e) {
reportError(null, e, ErrorManager.FLUSH_FAILURE);
} finally {
writerLock.readLock().unlock();
}
}
@Override
public synchronized void close() {
// Flush any in-flight content, though there should not actually be any because
// the generator is currently flushed in the synchronized publish() method.
flush();
// Close the generator and log file.
try {
if (generator != null) {
generator.close();
}
} catch (IOException | RuntimeException e) {
reportFailure("Unable to close", e, ErrorManager.CLOSE_FAILURE);
} finally {
generator = null;
counter = null;
}
}
private OutputStream createOutputStream() {
if (address != null || port >= 0) {
try {
if (protocol == Protocol.SSL_TCP) {
return new SslTcpOutputStream(address, port);
} else if (protocol == Protocol.UDP) {
return new UdpOutputStream(address, port);
} else {
return new TcpOutputStream(address, port);
}
} catch (IOException e) {
reportError("Failed to create socket output stream", e, ErrorManager.OPEN_FAILURE);
}
}
return null;
}
@Override
public void publish(LogRecord record) {
if (!isLoggable(record)) {
return;
}
// The formatter isn't necessarily thread-safe, so we synchronize around it.
String message;
synchronized (this) {
try {
message = getFormatter().format(record);
} catch (Exception ex) {
// We don't want to throw an exception here, but we
// report the exception to any registered ErrorManager.
reportError(null, ex, ErrorManager.FORMAT_FAILURE);
return;
}
}
VmApiProxyEnvironment environment = getThreadLocalEnvironment();
if (environment != null) {
environment.addLogRecord(convertLogRecord(record, message));
}
}
private synchronized void flushAndClose() throws SecurityException {
if (writer != null) {
try {
if (!doneHeader) {
writer.write(getFormatter().getHead(this));
doneHeader = true;
}
writer.write(getFormatter().getTail(this));
writer.flush();
writer.close();
} catch (Exception ex) {
// We don't want to throw an exception here, but we
// report the exception to any registered ErrorManager.
reportError(null, ex, ErrorManager.CLOSE_FAILURE);
}
writer = null;
}
}
@Override
public void close() {
closed = true;
writerLock.writeLock().lock();
try {
if (writer == null) {
return;
}
writer.write(getFormatter().getTail(this));
writer.flush();
writer.close();
writer = null;
} catch (final Exception e) {
reportError(null, e, ErrorManager.CLOSE_FAILURE);
} finally {
writerLock.writeLock().unlock();
}
// wait for bg tasks if running
backgroundTaskLock.lock();
backgroundTaskLock.unlock();
}
protected void closeWriter() {
writerLock.writeLock().lock();
try {
if (writer == null) {
return;
}
writer.write(getFormatter().getTail(this));
writer.flush();
writer.close();
writer = null;
date = "";
} catch (final Exception e) {
reportError(null, e, ErrorManager.CLOSE_FAILURE);
} finally {
writerLock.writeLock().unlock();
}
}
/**
* Flush the writer.
*/
@Override
public void flush() {
writerLock.readLock().lock();
try {
if (writer == null) {
return;
}
writer.flush();
} catch (final Exception e) {
reportError(null, e, ErrorManager.FLUSH_FAILURE);
} finally {
writerLock.readLock().unlock();
}
}
private void addNamedHandlersToCategory(CategoryConfig categoryConfig, Map<String, Handler> namedHandlers,
Logger categoryLogger,
ErrorManager errorManager) {
for (String categoryNamedHandler : categoryConfig.handlers.get()) {
if (namedHandlers.get(categoryNamedHandler) != null) {
categoryLogger.addHandler(namedHandlers.get(categoryNamedHandler));
} else {
errorManager.error(String.format("Handler with name '%s' is linked to a category but not configured.",
categoryNamedHandler), null, ErrorManager.GENERIC_FAILURE);
}
}
}
private static Handler configureFileHandler(final FileConfig config, final ErrorManager errorManager,
final List<LogCleanupFilterElement> filterElements) {
FileHandler handler = new FileHandler();
FileConfig.RotationConfig rotationConfig = config.rotation;
if ((rotationConfig.maxFileSize.isPresent() || rotationConfig.rotateOnBoot)
&& rotationConfig.fileSuffix.isPresent()) {
PeriodicSizeRotatingFileHandler periodicSizeRotatingFileHandler = new PeriodicSizeRotatingFileHandler();
periodicSizeRotatingFileHandler.setSuffix(rotationConfig.fileSuffix.get());
rotationConfig.maxFileSize
.ifPresent(memorySize -> periodicSizeRotatingFileHandler.setRotateSize(memorySize.asLongValue()));
periodicSizeRotatingFileHandler.setRotateOnBoot(rotationConfig.rotateOnBoot);
periodicSizeRotatingFileHandler.setMaxBackupIndex(rotationConfig.maxBackupIndex);
handler = periodicSizeRotatingFileHandler;
} else if (rotationConfig.maxFileSize.isPresent()) {
SizeRotatingFileHandler sizeRotatingFileHandler = new SizeRotatingFileHandler(
rotationConfig.maxFileSize.get().asLongValue(), rotationConfig.maxBackupIndex);
sizeRotatingFileHandler.setRotateOnBoot(rotationConfig.rotateOnBoot);
handler = sizeRotatingFileHandler;
} else if (rotationConfig.fileSuffix.isPresent()) {
PeriodicRotatingFileHandler periodicRotatingFileHandler = new PeriodicRotatingFileHandler();
periodicRotatingFileHandler.setSuffix(rotationConfig.fileSuffix.get());
handler = periodicRotatingFileHandler;
}
final PatternFormatter formatter = new PatternFormatter(config.format);
handler.setFormatter(formatter);
handler.setAppend(true);
try {
handler.setFile(config.path);
} catch (FileNotFoundException e) {
errorManager.error("Failed to set log file", e, ErrorManager.OPEN_FAILURE);
}
handler.setErrorManager(errorManager);
handler.setLevel(config.level);
handler.setFilter(new LogCleanupFilter(filterElements));
if (config.async.enable) {
return createAsyncHandler(config.async, config.level, handler);
}
return handler;
}
private static Handler configureSyslogHandler(final SyslogConfig config,
final ErrorManager errorManager,
final List<LogCleanupFilterElement> filterElements) {
try {
final SyslogHandler handler = new SyslogHandler(config.endpoint.getHostString(), config.endpoint.getPort());
handler.setAppName(config.appName.orElse(getProcessName()));
handler.setHostname(config.hostname.orElse(getQualifiedHostName()));
handler.setFacility(config.facility);
handler.setSyslogType(config.syslogType);
handler.setProtocol(config.protocol);
handler.setBlockOnReconnect(config.blockOnReconnect);
handler.setTruncate(config.truncate);
handler.setUseCountingFraming(config.useCountingFraming);
handler.setLevel(config.level);
final PatternFormatter formatter = new PatternFormatter(config.format);
handler.setFormatter(formatter);
handler.setErrorManager(errorManager);
handler.setFilter(new LogCleanupFilter(filterElements));
if (config.async.enable) {
return createAsyncHandler(config.async, config.level, handler);
}
return handler;
} catch (IOException e) {
errorManager.error("Failed to create syslog handler", e, ErrorManager.OPEN_FAILURE);
return null;
}
}
public static void disableCoS(Project p, final boolean enable) {
final AntProjectHelper helper = getAntProjectHelper(p);
if (helper == null) {
if (enable) {
StatusDisplayer.getDefault().setStatusText(
NbBundle.getMessage(ProjectHelper.class, "WARN_couldNotEnableCoS"),
StatusDisplayer.IMPORTANCE_ERROR_HIGHLIGHT);
}
return;
}
try {
ProjectManager.mutex().writeAccess(new Mutex.ExceptionAction<Void>() {
@Override
public Void run() throws Exception {
EditableProperties ep = helper.getProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH);
if (enable) {
ep.setProperty(JAXB_COMPILE_ON_SAVE, Boolean.TRUE.toString());
} else {
ep.remove(JAXB_COMPILE_ON_SAVE);
}
helper.putProperties(AntProjectHelper.PROJECT_PROPERTIES_PATH, ep);
return null;
}
});
} catch (MutexException ex) {
org.openide.ErrorManager.getDefault().notify(org.openide.ErrorManager.INFORMATIONAL, ex);
}
}
@Override
protected void doPublish(ExtLogRecord record) {
synchronized (this) {
if (!initialized) {
try {
initialize();
} catch (Exception e) {
reportError("Error creating fluentd connection", e, ErrorManager.OPEN_FAILURE);
setEnabled(false);
}
}
}
if (initialized) {
Map<String, Object> entries = new HashMap<>();
entries.put(Key.SEQUENCE.getKey(), record.getSequenceNumber());
entries.put(Key.LEVEL.getKey(), record.getLevel().getName());
entries.put(Key.THREAD_NAME.getKey(), record.getThreadName());
entries.put(Key.MESSAGE.getKey(), record.getFormattedMessage());
entries.put(Key.THREAD_ID.getKey(), record.getThreadID());
entries.put(Key.MDC.getKey(), record.getMdcCopy());
entries.put(Key.NDC.getKey(), record.getNdc());
this.sender.emit(this.tag, record.getMillis(), entries);
}
}
private void safeClose(RawSocketSender c) {
try {
if (c != null) {
c.close();
}
} catch (Exception e) {
reportError("Error closing resource", e, ErrorManager.CLOSE_FAILURE);
} catch (Throwable ignored) {
}
}
@Override
public synchronized void flush() {
try {
if (generator != null) {
generator.flush();
}
} catch (IOException | RuntimeException e) {
reportFailure("Unable to flush", e, ErrorManager.FLUSH_FAILURE);
}
}
/** Report logging failure to ErrorManager. Does not throw. */
private void reportFailure(String message, Exception e, int code) {
try {
ErrorManager manager = getErrorManager();
if (manager != null) {
manager.error(message, e, code);
}
} catch (Throwable t) {
// Failed to report logging failure. No meaningful action left.
}
}
public void publish(LogRecord record) {
if(! isLoggable(record)) return;
String formattedMessage;
try {
formattedMessage = getFormatter().formatMessage(record);
} catch(Exception e) {
reportError(null, e, ErrorManager.FORMAT_FAILURE);
return;
}
log4jLogger.callAppenders
( new XLoggingEvent(log4jLogger, record, formattedMessage) );
}
public void test_errorCheck() {
ErrorManager em = new ErrorManager();
MockStream aos = new MockStream();
PrintStream st = new PrintStream(aos);
System.setErr(st);
System.setOut(st);
em.error("supertest", null, ErrorManager.GENERIC_FAILURE);
st.flush();
assertTrue("message appears (supertest)", aos.getWrittenData().indexOf("supertest") != -1);
}
private void initialize() {
final Writer current = this.writer;
boolean okay = false;
try {
if (current != null) {
writeTail(current);
safeFlush(current);
}
final OutputStream out = createOutputStream();
if (out == null) {
return;
}
final String encoding = getEncoding();
final UninterruptibleOutputStream outputStream = new UninterruptibleOutputStream(out);
if (encoding == null) {
writer = new OutputStreamWriter(outputStream);
} else {
writer = new OutputStreamWriter(outputStream, encoding);
}
writeHead(writer);
okay = true;
} catch (UnsupportedEncodingException e) {
reportError("Error opening", e, ErrorManager.OPEN_FAILURE);
} finally {
safeClose(current);
if (!okay) {
safeClose(writer);
}
}
}
private void writeHead(final Writer writer) {
try {
final Formatter formatter = getFormatter();
if (formatter != null) writer.write(formatter.getHead(this));
} catch (Exception e) {
reportError("Error writing section header", e, ErrorManager.WRITE_FAILURE);
}
}
private void writeTail(final Writer writer) {
try {
final Formatter formatter = getFormatter();
if (formatter != null) writer.write(formatter.getTail(this));
} catch (Exception ex) {
reportError("Error writing section tail", ex, ErrorManager.WRITE_FAILURE);
}
}
private void safeClose(Closeable c) {
try {
if (c != null) c.close();
} catch (Exception e) {
reportError("Error closing resource", e, ErrorManager.CLOSE_FAILURE);
} catch (Throwable ignored) {
}
}
private void safeFlush(Flushable f) {
try {
if (f != null) f.flush();
} catch (Exception e) {
reportError("Error on flush", e, ErrorManager.FLUSH_FAILURE);
} catch (Throwable ignored) {
}
}