下面列出了怎么用java.util.logging.LogRecord的API类实例代码及写法,或者点击链接到github查看源代码。
private void createFolder(final File folder2Create, final String name) throws IOException {
boolean isSupported = new FileInfo(folder2Create).isSupportedFile();
ProvidedExtensions extensions = getProvidedExtensions();
if (!isSupported) {
extensions.createFailure(this, folder2Create.getName(), true);
FSException.io("EXC_CannotCreateFolder", folder2Create.getName(), getPath());// NOI18N
} else if (FileChangedManager.getInstance().exists(folder2Create)) {
extensions.createFailure(this, folder2Create.getName(), true);
SyncFailedException sfe = new SyncFailedException(folder2Create.getAbsolutePath()); // NOI18N
String msg = NbBundle.getMessage(FileBasedFileSystem.class, "EXC_CannotCreateFolder", folder2Create.getName(), getPath()); // NOI18N
Exceptions.attachLocalizedMessage(sfe, msg);
throw sfe;
} else if (!folder2Create.mkdirs()) {
extensions.createFailure(this, folder2Create.getName(), true);
FSException.io("EXC_CannotCreateFolder", folder2Create.getName(), getPath());// NOI18N
}
LogRecord r = new LogRecord(Level.FINEST, "FolderCreated: "+ folder2Create.getAbsolutePath());
r.setParameters(new Object[] {folder2Create});
Logger.getLogger("org.netbeans.modules.masterfs.filebasedfs.fileobjects.FolderObj").log(r);
}
/**
* Entry point for creating and display a 'stack trace report' window, a window which provides a
* basic UI where users can enter an error description before uploading an error report. The
* window is tied to a stack trace or error that happened and would be uploaded as part of the
* report. The user description is for developer benefit to get an opportunity for more
* information around the circumstances of an error.
*/
static void showWindow(
final Component parentWindow, final ErrorReportClient uploader, final LogRecord logRecord) {
final StackTraceReportView window = new StackTraceReportSwingView(parentWindow);
final StackTraceReportModel viewModel =
StackTraceReportModel.builder()
.view(window)
.stackTraceRecord(logRecord)
.formatter(new StackTraceErrorReportFormatter())
.uploader(
ErrorReportUploadAction.builder()
.serviceClient(uploader)
.successConfirmation(ConfirmationDialogController::showSuccessConfirmation)
.failureConfirmation(ConfirmationDialogController::showFailureConfirmation)
.build())
.preview(new ReportPreviewSwingView(parentWindow))
.build();
window.bindActions(viewModel);
window.show();
}
@Override
public final void publish(LogRecord record) {
if (abstractHandler) {
throw new IllegalArgumentException("May not log to abstract handler");
}
if (record instanceof EventLogRecord) {
try {
publishEvent((EventLogRecord) record);
} catch (IOException e) {
throw new IllegalStateException("Unable to log an event", e);
}
} else {
LOGGER.warn("Unable to Event log an record of class: {}", record.getClass().getCanonicalName());
throw new IllegalArgumentException("Invalid class for event log: " + record.getClass().getCanonicalName() );
}
}
/** Sends info to UI handler about NetBeans APIs in use
*/
private static void logNetBeansAPIUsage(String msg, Collection<ModuleDependency> deps) {
List<String> cnbs = new ArrayList<String>();
for (ModuleDependency moduleDependency : deps) {
String cnb = moduleDependency.getModuleEntry().getCodeNameBase();
// observe just NetBeans API module usage
if (cnb.startsWith("org.openide") || cnb.startsWith("org.netbeans")) { // NOI18N
cnbs.add(cnb);
}
}
if (cnbs.isEmpty()) {
return;
}
LogRecord rec = new LogRecord(Level.CONFIG, msg);
rec.setParameters(cnbs.toArray(new String[0]));
rec.setResourceBundleName(SingleModuleProperties.class.getPackage().getName() + ".Bundle"); // NOI18N
rec.setResourceBundle(NbBundle.getBundle(SingleModuleProperties.class));
rec.setLoggerName(UI_LOG.getName());
UI_LOG.log(rec);
}
@Override
public String format(LogRecord record) {
StringWriter buffer = new StringWriter(256);
buffer.append(format.format(record.getMillis()));
buffer.append(" ");
buffer.append(record.getLevel().getName());
buffer.append(" ");
buffer.append(record.getSourceClassName());
buffer.append(".");
buffer.append(record.getSourceMethodName());
buffer.append(": ");
buffer.append(record.getMessage());
buffer.append("\n");
if (record.getThrown() != null) {
PrintWriter pw = new PrintWriter(buffer);
record.getThrown().printStackTrace(pw);
pw.close();
}
// else nothing since StringWriter.close() is a no-op
return buffer.toString();
}
/**
* Tests with a CRS having wrong axis order.
*
* @throws FactoryException if an error occurred while querying the authority factory.
*/
@Test
@DependsOnMethod("testNormalizedCRS")
public void testDifferentAxisOrder() throws FactoryException {
final Map<String,Object> properties = new HashMap<>(4);
properties.put(DefaultGeographicCRS.NAME_KEY, "WGS 84");
properties.put(DefaultGeographicCRS.IDENTIFIERS_KEY, new NamedIdentifier(HardCodedCitations.EPSG, "4326"));
DefaultGeographicCRS crs = HardCodedCRS.WGS84;
crs = new DefaultGeographicCRS(properties, crs.getDatum(), crs.getCoordinateSystem());
final DefinitionVerifier ver = DefinitionVerifier.withAuthority(crs, null, false);
assertNotNull("Should replace by normalized CRS", ver);
assertNotSame("Should replace by normalized CRS", crs, ver.authoritative);
assertSame ("Should replace by normalized CRS", CommonCRS.WGS84.normalizedGeographic(), ver.authoritative);
final LogRecord warning = ver.warning(true);
assertNotNull("Should emit a warning.", warning);
final String message = new SimpleFormatter().formatMessage(warning);
assertTrue(message, message.contains("WGS 84"));
assertTrue(message, message.contains("EPSG:4326"));
}
@Override
public String format(LogRecord record) {
StringBuilder b = new StringBuilder();
b.append(dateFormat.format(new Date(record.getMillis())));
b.append(" ");
b.append(record.getLevel().getLocalizedName());
b.append(": ");
b.append(formatMessage(record));
String className = record.getSourceClassName();
if (className != null) {
int dot = className.lastIndexOf('.');
if (dot != -1) {
className = className.substring(dot + 1);
}
b.append(" (").append(className).append(".").append(record.getSourceMethodName()).append("())");
}
b.append("\n");
append(record.getThrown(), b);
return b.toString();
}
private static LogAdviceTraveler onBeforeCommon(ThreadContext context, LogRecord record,
Level level) {
// cannot check Logger.getFilter().isLoggable(LogRecord) because the Filter object
// could be stateful and might alter its state (e.g.
// com.sun.mail.util.logging.DurationFilter)
String formattedMessage = nullToEmpty(formatter.formatMessage(record));
int lvl = level.intValue();
Throwable t = record.getThrown();
if (LoggerPlugin.markTraceAsError(lvl >= Level.SEVERE.intValue(),
lvl >= Level.WARNING.intValue(), t != null)) {
context.setTransactionError(formattedMessage, t);
}
TraceEntry traceEntry =
context.startTraceEntry(new LogMessageSupplier(level.getName().toLowerCase(),
record.getLoggerName(), formattedMessage), timerName);
return new LogAdviceTraveler(traceEntry, lvl, formattedMessage, t);
}
static void setupLogging() {
final long start = currentTimeMillis();
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.FINE);
handler.setFormatter(new Formatter() {
@Override
public String format(LogRecord record) {
return String.format("%7d - %s%n", record.getMillis() - start, record.getMessage());
}
});
Logger[] loggers = {
Logger.getLogger(DenominatorD.class.getPackage().getName()),
Logger.getLogger(feign.Logger.class.getName()),
Logger.getLogger(MockWebServer.class.getName())
};
for (Logger logger : loggers) {
logger.setLevel(Level.FINE);
logger.setUseParentHandlers(false);
logger.addHandler(handler);
}
}
/**
* Creates a string formatted in markdown. If we have an exception we'll log the full exception
* name and stack trace. If there is a log message we will log it, this might be redundant to the
* exception message (but that is okay!). Otherwise we will log base information like OS, TripleA
* version and Java version.
*/
private String buildBody(@Nullable final String userDescription, final LogRecord logRecord) {
return Optional.ofNullable(Strings.emptyToNull(userDescription))
.map(description -> "## User Description\n" + description + "\n\n")
.orElse("")
+ Optional.ofNullable(logRecord.getMessage())
.map(msg -> "## Log Message\n" + msg + "\n\n")
.orElse("")
+ "## TripleA Version\n"
+ ClientContext.engineVersion()
+ "\n\n"
+ "## Java Version\n"
+ SystemProperties.getJavaVersion()
+ "\n\n"
+ "## Operating System\n"
+ SystemProperties.getOperatingSystem()
+ "\n\n"
+ Optional.ofNullable(logRecord.getThrown())
.map(StackTraceErrorReportFormatter::throwableToString)
.orElse("");
}
/**
* Test for the {@link AbstractLog#warn(String)} method.
*/
@Test
public void testWarnString() {
final String method = "testWarnString";
final String messsage = "Warning Message";
final Level level = Level.WARNING;
myTestLog.warn(messsage);
final List<LogRecord> records = myCaptureHandler.getRecords();
assertThat(records.size(), is(1));
final LogRecord record = records.get(0);
assertThat(record.getLevel(), is(level));
assertThat(record.getLoggerName(), is(JulLogTest.class.getName()));
assertThat(record.getMessage(), is(messsage));
assertThat(record.getSourceClassName(), is(JulLogTest.class.getName()));
assertThat(record.getSourceMethodName(), is(method));
assertThat(record.getThreadID(), is((int) Thread.currentThread()
.getId()));
assertThat(record.getThrown(), nullValue());
}
@RandomlyFails
public void testBLE91246() throws Exception {
final boolean wasThrown[] = new boolean[1];
Logger.getLogger(Utilities.class.getName()).addHandler(new Handler() {
public void publish(LogRecord lr) {
if (lr.getThrown() != null && lr.getThrown().getClass() == BadLocationException.class) {
wasThrown[0] = true;
}
}
public void close() {}
public void flush() {}
});
performTest("BLE91246");
assertFalse("BLE was not thrown", wasThrown[0]);
}
@Override
public String format( LogRecord record ) {
// Center the level
int totalSpaces = LEVEL_SPAN - record.getLevel().toString().length();
StringBuilder sbLevel = new StringBuilder();
for( int i=0; i<totalSpaces/2; i++ )
sbLevel.append( " " );
sbLevel.append( record.getLevel());
for( int i=sbLevel.toString().length(); i<LEVEL_SPAN; i++ )
sbLevel.append( " " );
// Format the entire record
StringBuilder sb = new StringBuilder();
sb.append( "[ " ).append( this.df.format( new Date( record.getMillis()))).append(" ]" );
sb.append( "[ ").append( sbLevel ).append( " ] " );
sb.append( record.getSourceClassName()).append("#");
sb.append( record.getSourceMethodName());
sb.append( "\n" );
sb.append( formatMessage( record ));
sb.append( "\n" );
return sb.toString();
}
@Override
public void publish(LogRecord record) {
if (!isLoggable(record)) {
return;
}
pl.brightinventions.slf4android.LogRecord slfRecord = pl.brightinventions.slf4android.LogRecord.fromRecord(record);
int level = slfRecord.getLogLevel().getAndroidLevel();
String tag = record.getLoggerName();
try {
String message = logRecordFormatter.format(slfRecord);
Log.println(level, tag, message);
} catch (RuntimeException e) {
Log.e("LogcatHandler", "Error logging message.", e);
}
}
/**
* Deserializes the Base64 encoded string returned by {@link
* #getBase64()}, format the obtained LogRecord using a
* SimpleFormatter, and checks that the string representation obtained
* matches the original string representation returned by {@link
* #getString()}.
*/
protected void dotest() {
try {
final String base64 = getBase64();
final ByteArrayInputStream bais =
new ByteArrayInputStream(Base64.getDecoder().decode(base64));
final ObjectInputStream ois = new ObjectInputStream(bais);
final LogRecord record = (LogRecord)ois.readObject();
final SimpleFormatter formatter = new SimpleFormatter();
String expected = getString();
String str2 = formatter.format(record);
check(expected, str2);
System.out.println(str2);
System.out.println("PASSED: "+this.getClass().getName()+"\n");
} catch (IOException | ClassNotFoundException x) {
throw new RuntimeException(x);
}
}
/**
* test that {0} etc is replaced properly
*/
@Test
public void testTextFormatting () {
VespaFormatter formatter = new VespaFormatter(serviceName, app);
LogRecord testRecord = new LogRecord(Level.INFO, "this {1} is {0} test");
testRecord.setInstant(Instant.ofEpochMilli(1098709021843L));
testRecord.setThreadID(123);
testRecord.setLoggerName("org.foo");
Object[] params = { "a small", "message" };
testRecord.setParameters(params);
String expected = "1098709021.843000\t"
+ hostname + "\t"
+ pid
+ "/123" + "\t"
+ "serviceName\t"
+ app
+ ".org.foo\t"
+ "info\t"
+ "this message is a small test\n";
assertEquals(expected, formatter.format(testRecord));
}
private void log(Level level, Object message, Throwable t, Object... params) {
if (!logger.isLoggable(level)) {
return;
}
String msg = (message == null) ? "NULL" : message.toString();
LogRecord record = new LogRecord(level, msg);
record.setLoggerName(logger.getName());
if (t != null) {
record.setThrown(t);
} else if (params != null && params.length != 0 && params[params.length - 1] instanceof Throwable) {
// The exception may be the last parameters (SLF4J uses this convention).
// As the logger can be used in a SLF4J style, we need to check
record.setThrown((Throwable) params[params.length - 1]);
}
record.setSourceClassName(null);
record.setParameters(params);
logger.log(record);
}
@Test
public void testSymbolicLinkSetter() throws Exception {
SimpleLogHandler handler =
SimpleLogHandler.builder()
.setPrefix(tmp.getRoot() + File.separator + "hello")
.setSymlinkName("bye")
.build();
handler.publish(new LogRecord(Level.SEVERE, "Hello world")); // To open the log file.
if (OS.getCurrent() == OS.WINDOWS) {
// On Windows, by default, only administrator accounts can create symbolic links.
assertThat(handler.getSymbolicLinkPath()).isEmpty();
} else {
assertThat(handler.getSymbolicLinkPath()).isPresent();
assertThat(handler.getSymbolicLinkPath().get().toString())
.isEqualTo(tmp.getRoot() + File.separator + "bye");
assertThat(Files.isSymbolicLink(handler.getSymbolicLinkPath().get())).isTrue();
assertThat(Files.readSymbolicLink(handler.getSymbolicLinkPath().get()).toString())
.isEqualTo(handler.getCurrentLogFilePath().get().getFileName().toString());
}
}
/**
* Test for the {@link AbstractLog#info(String, Object...)} method.
*/
@Test
public void testInfoStringObjectArray() {
final String method = "testInfoStringObjectArray";
final String messsage = "Info - Hello {}"; // "Info - Hello World";
final Level level = Level.INFO;
myTestLog.info("Info - Hello {}", "World");
final List<LogRecord> records = myCaptureHandler.getRecords();
assertThat(records.size(), is(1));
final LogRecord record = records.get(0);
assertThat(record.getLevel(), is(level));
assertThat(record.getLoggerName(), is(Slf4jLogTest.class.getName()));
assertThat(record.getMessage(), is(messsage));
assertThat(record.getSourceClassName(),
is(Slf4jLogTest.class.getName()));
assertThat(record.getSourceMethodName(), is(method));
assertThat(record.getThrown(), nullValue());
}
protected void fireErrorOccurredEvent(LogRecord message)
{
PCGenTaskEvent taskEvent = null;
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2)
{
if (listeners[i] == PCGenTaskListener.class)
{
// Lazily create the event:
if (taskEvent == null)
{
taskEvent = new PCGenTaskEvent(this, message);
}
((PCGenTaskListener) listeners[i + 1]).errorOccurred(taskEvent);
}
}
}
@Test
public void testSymbolicLinkInitiallyInvalidReplaced() throws Exception {
if (OS.getCurrent() == OS.WINDOWS) {
// On Windows, by default, only administrator accounts can create symbolic links.
return;
}
Path symlinkPath = Paths.get(tmp.getRoot().toString(), "hello");
Files.createSymbolicLink(symlinkPath, Paths.get("no-such-file"));
// Expected to delete the (invalid) symlink and replace with a symlink to the log
SimpleLogHandler handler =
SimpleLogHandler.builder().setPrefix(symlinkPath.toString()).build();
handler.publish(new LogRecord(Level.SEVERE, "Hello world")); // To open the log file.
assertThat(handler.getSymbolicLinkPath().get().toString()).isEqualTo(symlinkPath.toString());
assertThat(Files.isSymbolicLink(handler.getSymbolicLinkPath().get())).isTrue();
assertThat(Files.readSymbolicLink(handler.getSymbolicLinkPath().get()).toString())
.isEqualTo(handler.getCurrentLogFilePath().get().getFileName().toString());
}
private static Logger instantiateLogger(final String name, final Level level) {
final Logger logger = java.util.logging.Logger.getLogger(name);
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
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 null;
}
}, createLoggerControlAccCtxt());
return logger;
}
@Override
public void publish(LogRecord record) {
if (!isLoggable(record)) {
return;
}
// fill source entries, before we hand the record over to another
// thread with another class loader
record.getSourceMethodName();
LogEntry entry = new LogEntry(record, this);
boolean added = false;
try {
while (!added && !queue.offer(entry)) {
switch (OVERFLOW_DROP_TYPE) {
case OVERFLOW_DROP_LAST: {
//remove the last added element
queue.pollLast();
break;
}
case OVERFLOW_DROP_FIRST: {
//remove the first element in the queue
queue.pollFirst();
break;
}
case OVERFLOW_DROP_FLUSH: {
added = queue.offer(entry, 1000, TimeUnit.MILLISECONDS);
break;
}
case OVERFLOW_DROP_CURRENT: {
added = true;
break;
}
}//switch
}//while
} catch (InterruptedException x) {
// Allow thread to be interrupted and back out of the publish
// operation. No further action required.
}
}
/**
* Tests {@link StoreListeners#warning(String, Exception)} with a registered listener.
*/
@Test
@DependsOnMethod("testAddAndRemoveStoreListener")
public void testWarning() {
final LogRecord record = new LogRecord(Level.WARNING, "The message");
store.addListener(WarningEvent.class, this);
store.listeners().warning(record);
assertSame(record, warning);
}
@Test
public void testWithArguments() {
LogData data = FakeLogData.withBraceStyle("Answer={0}", 42).setLevel(Level.FINE);
LogRecord record = SimpleLogRecord.create(data);
assertThat(record.getLevel()).isEqualTo(Level.FINE);
assertThat(record.getMessage()).isEqualTo("Answer=42");
assertThat(record.getParameters()).isNull();
}
public void transferThreadTempLogsToSessionLogs(SessionId sessionId) {
ThreadKey threadId = new ThreadKey();
List<LogRecord> threadRecords = perThreadTempRecords.get(threadId);
List<LogRecord> sessionRecords = perSessionRecords.get(sessionId);
if (threadRecords != null) {
if (sessionRecords == null) {
sessionRecords = new ArrayList<>();
perSessionRecords.put(sessionId, sessionRecords);
}
sessionRecords.addAll(threadRecords);
}
clearThreadTempLogs();
}
public String getLogOutput() {
SimpleFormatter formatter = new SimpleFormatter();
StringBuilder sb = new StringBuilder();
for (LogRecord loggedMessage : loggedMessages) {
sb.append(formatter.format(loggedMessage));
}
return sb.toString();
}
@Override
public void publish(LogRecord record) {
if (Thread.currentThread() == thread) {
cnt++;
isRP &= rp.isRequestProcessorThread();
}
}
@OnBefore
public static @Nullable LogAdviceTraveler onBefore(ThreadContext context,
@BindParameter @Nullable LogRecord record, @BindReceiver Object logger) {
if (record == null) {
return null;
}
Level level = record.getLevel();
if (!((Logger) logger).isLoggable(level)) {
// Logger.log(LogRecord) was called directly
return null;
}
return onBeforeCommon(context, record, level);
}
@Override
public String format(LogRecord record)
{
StringBuilder output = new StringBuilder();
output.append('[');
output.append(dateFmt.format(new Date(record.getMillis())));
output.append(']');
output.append(' ');
output.append(record.getMessage());
for (Object p : record.getParameters())
{
if (p == null) continue;
output.append(',');
output.append(' ');
if (p instanceof L2ItemInstance)
{
L2ItemInstance item = (L2ItemInstance)p;
output.append("item " + item.getObjectId() + ":");
if (item.getEnchantLevel() > 0) output.append("+" + item.getEnchantLevel() + " ");
output.append(item.getItem().getName());
output.append("(" + item.getCount() + ")");
}
//else if (p instanceof L2PcInstance)
// output.append(((L2PcInstance)p).getName());
else output.append(p.toString()/* + ":" + ((L2Object)p).getObjectId()*/);
}
output.append(CRLF);
return output.toString();
}