下面列出了java.util.logging.LogRecord#setSourceClassName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void format() {
final LogRecord record = new LogRecord(Level.FINE, "test message");
record.setLoggerName("logger");
record.setLevel(Level.FINER);
record.setMillis(123456789);
record.setSourceClassName("my.class.Name");
record.setSourceMethodName("aMethod");
// default
assertEquals(
"Jan 02, 1970 my.class.Name aMethod\nFINER: test message\n",
new LocalFileHandler.PatternFormatter("%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%6$s%n", Locale.ENGLISH)
.format(record).replace("\r", "").replaceFirst("1970.*my"/*skip time*/, "1970 my"));
// simple
assertEquals(
"test message\n",
new LocalFileHandler.PatternFormatter("%5$s%n", Locale.ENGLISH).format(record).replace("\r", ""));
final String custom = new LocalFileHandler.PatternFormatter("%1$tY-%1$tM-%1$td %1$tT [%4$5s][%7$s] %5$s%6$s%n", Locale.ENGLISH)
.format(record).replace("\r", "");
assertTrue(custom
.matches("1970\\-17\\-02 \\p{Digit}+\\:17\\:36 \\[FINER\\]\\[my\\.class\\.Name\\] test message\\\n"));
}
/**
* Invoked after we finished to create all tables. This method flush the warnings
* (omitting duplicated warnings), then returns all tables including dependencies.
*/
final Collection<Table> finish() throws DataStoreException {
for (final Table table : tables.values()) {
table.setDeferredSearchTables(this, tables);
}
for (final ResourceInternationalString warning : warnings) {
final LogRecord record = warning.toLogRecord(Level.WARNING);
record.setSourceClassName(SQLStore.class.getName());
record.setSourceMethodName("components"); // Main public API trigging the database analysis.
listeners.warning(record);
}
return tables.values();
}
private void inferCaller( Class wrapperClass, LogRecord lrec )
{
// Private method to infer the caller's class and method names
// Get the stack trace.
StackTraceElement stack[] = (new Throwable()).getStackTrace();
StackTraceElement frame = null ;
String wcname = wrapperClass.getName() ;
String baseName = LogWrapperBase.class.getName() ;
// The top of the stack should always be a method in the wrapper class,
// or in this base class.
// Search back to the first method not in the wrapper class or this class.
int ix = 0;
while (ix < stack.length) {
frame = stack[ix];
String cname = frame.getClassName();
if (!cname.equals(wcname) && !cname.equals(baseName)) {
break;
}
ix++;
}
// Set the class and method if we are not past the end of the stack
// trace
if (ix < stack.length) {
lrec.setSourceClassName(frame.getClassName());
lrec.setSourceMethodName(frame.getMethodName());
}
}
@SuppressWarnings("deprecation") // setMillis is deprecated in JDK 9
protected Object writeReplace() {
LogRecord serialized = new LogRecord(getLevel(), getMessage());
serialized.setLoggerName(getLoggerName());
serialized.setResourceBundle(getResourceBundle());
serialized.setResourceBundleName(getResourceBundleName());
serialized.setSourceClassName(getSourceClassName());
serialized.setSourceMethodName(getSourceMethodName());
serialized.setSequenceNumber(getSequenceNumber());
serialized.setParameters(getParameters());
serialized.setThreadID(getThreadID());
serialized.setMillis(getMillis());
serialized.setThrown(getThrown());
return serialized;
}
/**
* Reports a warning.
*
* @param source the class to report as the warning emitter.
* @param method the method to report as the warning emitter.
* @param record the warning to report.
*/
private void warning(final Class<?> source, final String method, final LogRecord record) {
record.setSourceClassName(source.getCanonicalName());
record.setSourceMethodName(method);
record.setLoggerName(Loggers.SQL);
if (logFilter == null || logFilter.isLoggable(record)) {
LOGGER.log(record);
}
}
/**
* Logs the given record. This is used only when we can not use the {@link #warning warning methods},
* or when the information is not worth to report as a warning.
*/
final void log(final LogRecord record) {
Logger logger = Logging.getLogger(Loggers.WKT);
record.setSourceClassName(getPublicFacade());
record.setSourceMethodName(getFacadeMethod());
record.setLoggerName(logger.getName());
logger.log(record);
}
@Test
public void assertTestFormatting() throws IOException {
Level level = Level.SEVERE;
long recordMillis = 874400705000L;
String recordSourceClassName = "org.my.test.Class";
String recordSourceMethodName = "mySourceMethod";
String recordMessage = "Formatting Log Message";
Throwable throwable = new Throwable() {
public void printStackTrace(PrintWriter s) {
StackTraceElement[] trace = getStackTrace();
for (StackTraceElement traceElement : trace) {
s.println("\tat " + traceElement);
}
}
};
StackTraceElement recordStackTrace1 = new StackTraceElement("declaringClass", "methodName", "fileName.java", 1);
StackTraceElement recordStackTrace2 = new StackTraceElement("declaringClass2", "methodName2.drl.java",
"fileName2.java", 2);
StackTraceElement recordStackTrace3 = new StackTraceElement("declaringClass", "methodName.apk.java", "fileName",
3);
StackTraceElement[] recordStackTrace = { recordStackTrace1, recordStackTrace2, recordStackTrace3 };
throwable.setStackTrace(recordStackTrace);
LogRecord record = new LogRecord(level, recordMessage);
record.setMillis(recordMillis);
record.setSourceClassName(recordSourceClassName);
record.setSourceMethodName(recordSourceMethodName);
record.setMessage(recordMessage);
record.setThrown(throwable);
String expectedOutput = "Sep 16, 1997 09:05:05 org.my.test.Class mySourceMethod()" + lineSeparator()
+ "Message: Formatting Log Message" + lineSeparator()
+ "\tat declaringClass.methodName(fileName.java:1)" + lineSeparator()
+ "\tat declaringClass2.methodName2.drl.java(fileName2.java:2)" + lineSeparator()
+ "\tat declaringClass.methodName.apk.java(fileName:3)" + lineSeparator();
assertEquals(expectedOutput, LSPClientLogHandler.formatRecord(record, Locale.US));
}
public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) {
if (isLoggable(level)) {
LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
lr.setThrown(thrown);
doLog(lr);
}
}
public void log( Exception ex )
{
if ( logger.isLoggable( Level.WARNING ) )
{
LogRecord lr = new LogRecord( Level.WARNING, "Exception" ); //$NON-NLS-1$
lr.setThrown( ex );
String[] rt = inferCaller( );
lr.setSourceClassName( rt[0] );
lr.setSourceMethodName( rt[1] );
logger.log( lr );
}
}
public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, final String msg) {
if (isLoggable(level)) {
final LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
doLog(lr, bundleName);
}
}
public void throwing(String sourceClass, String sourceMethod, Throwable thrown) {
if (isLoggable(Level.FINER)) {
LogRecord lr = new LogRecord(Level.FINER, "THROW");
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
lr.setThrown(thrown);
doLog(lr);
}
}
public void logp(Level level, String sourceClass, String sourceMethod, String msg, Throwable thrown) {
if (isLoggable(level)) {
LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
lr.setThrown(thrown);
doLog(lr);
}
}
public void logp(Level level, String sourceClass, String sourceMethod, String msg, Object param1) {
if (isLoggable(level)) {
LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
Object params[] = {param1 };
lr.setParameters(params);
doLog(lr);
}
}
private void inferCaller( Class wrapperClass, LogRecord lrec )
{
// Private method to infer the caller's class and method names
// Get the stack trace.
StackTraceElement stack[] = (new Throwable()).getStackTrace();
StackTraceElement frame = null ;
String wcname = wrapperClass.getName() ;
String baseName = LogWrapperBase.class.getName() ;
// The top of the stack should always be a method in the wrapper class,
// or in this base class.
// Search back to the first method not in the wrapper class or this class.
int ix = 0;
while (ix < stack.length) {
frame = stack[ix];
String cname = frame.getClassName();
if (!cname.equals(wcname) && !cname.equals(baseName)) {
break;
}
ix++;
}
// Set the class and method if we are not past the end of the stack
// trace
if (ix < stack.length) {
lrec.setSourceClassName(frame.getClassName());
lrec.setSourceMethodName(frame.getMethodName());
}
}
public void warn(String s) {
LogRecord lr = new LogRecord(Level.WARNING, s);
lr.setSourceClassName(log.getName());
log.log(lr);
}
private LogRecord buildLogRecord( Level level, String message ) {
LogRecord record = new LogRecord( level, message );
record.setSourceClassName( configuration.programFilepath().getName() );
return record;
}
/**
* Implementation of {@link #unexpectedException(Logger, Class, String, Throwable)}.
*
* @param logger where to log the error, or {@code null} for inferring a default value from other arguments.
* @param classe the fully qualified class name where the error occurred, or {@code null} for inferring a default value from other arguments.
* @param method the method where the error occurred, or {@code null} for inferring a default value from other arguments.
* @param error the error, or {@code null} if none.
* @param level the logging level.
* @return {@code true} if the error has been logged, or {@code false} if the given {@code error}
* was null or if the logger does not log anything at the specified level.
*/
private static boolean unexpectedException(Logger logger, String classe, String method,
final Throwable error, final Level level)
{
/*
* Checks if loggable, inferring the logger from the classe name if needed.
*/
if (error == null) {
return false;
}
if (logger == null && classe != null) {
final int separator = classe.lastIndexOf('.');
final String paquet = (separator >= 1) ? classe.substring(0, separator-1) : "";
logger = getLogger(paquet);
}
if (logger != null && !logger.isLoggable(level)) {
return false;
}
/*
* The message is fetched using Exception.getMessage() instead than getLocalizedMessage()
* because in a client-server architecture, we want the locale on the server-side instead
* than the locale on the client side. See LocalizedException policy.
*/
final StringBuilder buffer = new StringBuilder(256).append(Classes.getShortClassName(error));
String message = error.getMessage(); // Targeted to system administrators (see above).
if (message != null) {
buffer.append(": ").append(message);
}
message = buffer.toString();
message = Exceptions.formatChainedMessages(null, message, error);
final LogRecord record = new LogRecord(level, message);
if (level.intValue() >= LEVEL_THRESHOLD_FOR_STACKTRACE) {
record.setThrown(error);
}
if (logger == null || classe == null || method == null) {
logger = inferCaller(logger, classe, method, error.getStackTrace(), record);
} else {
record.setSourceClassName(classe);
record.setSourceMethodName(method);
}
record.setLoggerName(logger.getName());
logger.log(record);
return true;
}
public void error(String s) {
LogRecord lr = new LogRecord(Level.SEVERE, s);
lr.setSourceClassName(log.getName());
log.log(lr);
}
/**
* Forwards StAX warnings to {@link DataStore} listeners.
* This method is invoked by {@link XMLStreamReader} when needed.
*
* @param message the message to put in a logging record.
* @param errorType ignored.
* @param info ignored.
* @param location ignored.
*/
@Override
public void report(String message, String errorType, Object info, Location location) {
final LogRecord record = new LogRecord(Level.WARNING, message);
record.setSourceClassName(StaxDataStore.this.getClass().getCanonicalName());
// record.setLoggerName(…) will be invoked by 'listeners' with inferred name.
listeners.warning(record);
}
/**
* Reports a warning contained in the given {@link LogRecord}.
* Note that the given record will not necessarily be sent to the logging framework;
* if the user as registered at least one listener, then the record will be sent to the listeners instead.
*
* <p>This method sets the {@linkplain LogRecord#setSourceClassName(String) source class name} and
* {@linkplain LogRecord#setSourceMethodName(String) source method name} to hard-coded values.
* Those values assume that the warnings occurred indirectly from a call to {@link #getMetadata()}
* in this class. We do not report private classes or methods as the source of warnings.</p>
*
* @param record the warning to report.
*/
final void warning(final LogRecord record) {
// Logger name will be set by listeners.warning(record).
record.setSourceClassName(GeoTiffStore.class.getName());
record.setSourceMethodName("getMetadata");
listeners.warning(record);
}