下面列出了java.util.logging.LogRecord#getLoggerName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public boolean isLoggable(LogRecord record)
{
if (record.getLoggerName() != "item") return false;
if (_excludeProcess != null)
{
//if (record.getMessage() == null) return true;
String[] messageList = record.getMessage().split(":");
if (messageList.length < 2 || !_excludeProcess.contains(messageList[1])) return true;
}
if (_excludeItemType != null)
{
//if (record.getParameters() == null || record.getParameters().length == 0 || !(record.getParameters()[0] instanceof L2ItemInstance)) return true;
L2ItemInstance item = ((L2ItemInstance)record.getParameters()[0]);
if (!_excludeItemType.contains(item.getItemType().toString())) return true;
}
return (_excludeProcess == null && _excludeItemType == null);
}
@Override
public String format(final LogRecord record) {
dat.setTime(record.getMillis());
String source;
if (record.getSourceClassName() != null) {
source = record.getSourceClassName();
if (record.getSourceMethodName() != null) {
source += " " + record.getSourceMethodName();
}
} else {
source = record.getLoggerName();
}
final String message = formatMessage(record);
String throwable = "";
if (record.getThrown() != null) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
pw.println();
record.getThrown().printStackTrace(pw);
pw.close();
throwable = sw.toString();
}
return String.format(format, dat, source, record.getLoggerName(), record.getLevel(), message,
throwable);
}
/**
* A Custom format implementation that is designed for brevity.
*/
public String format(LogRecord record) {
String loggerName = record.getLoggerName();
if (loggerName == null) {
loggerName = "root";
}
StringBuilder output = new StringBuilder()
.append(loggerName)
.append("[")
.append(record.getLevel()).append('|')
.append(Thread.currentThread().getName()).append('|')
.append(format.format(new Date(record.getMillis())))
.append("]: ")
.append(record.getMessage()).append(' ')
.append(lineSep);
return output.toString();
}
@Override
public void publish(LogRecord record) {
if (!isLoggable(record)) {
return;
}
int severity = IStatus.INFO;
if (record.getLevel() == Level.SEVERE) {
severity = IStatus.ERROR;
} else if (record.getLevel() == Level.WARNING) {
severity = IStatus.WARNING;
}
IStatus status = new Status(severity, record.getLoggerName(), record.getMessage(), record.getThrown());
Platform.getLog(JavaDebuggerServerPlugin.context.getBundle()).log(status);
}
/** {@inheritDoc} */
@Override public String format(LogRecord record) {
String threadName = Thread.currentThread().getName();
String logName = record.getLoggerName();
if (logName == null)
logName = ANONYMOUS_LOGGER_NAME;
else if (logName.contains("."))
logName = logName.substring(logName.lastIndexOf('.') + 1);
String ex = null;
if (record.getThrown() != null) {
StringWriter sw = new StringWriter();
record.getThrown().printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();
ex = "\n" + stackTrace;
}
return "[" + DATE_FORMATTER.get().format(new Date(record.getMillis())) + "][" +
record.getLevel() + "][" +
threadName + "][" +
logName + "] " +
formatMessage(record) +
(ex == null ? "\n" : ex);
}
/**
* Retrieves a java.util.Logging filter used to ensure that only LogRecords whose
* logger names start with any of the required prefixes are logged.
*
* @param requiredPrefixes A non-null list of prefixes to be matched with the LogRecord logger names.
* @return A java.util.logging Filter that only permits logging LogRecords whose
* logger names start with any of the required prefixes.
*/
public static Filter getLoggingFilter(final String... requiredPrefixes) {
// Check sanity
Validate.notNull(requiredPrefixes, "requiredPrefixes");
// All done.
return new Filter() {
// Internal state
private List<String> requiredPrefs = Arrays.asList(requiredPrefixes);
@Override
public boolean isLoggable(final LogRecord record) {
final String loggerName = record.getLoggerName();
for (String current : requiredPrefs) {
if (loggerName.startsWith(current)) {
return true;
}
}
// No matches found.
return false;
}
};
}
/**
* <p>Format the given log record and return the formatted string.</p>
*
* <p>The resulting formatted String will normally include a localized
* and formated version of the LogRecord's message field.</p>
*
* @param record the log record to be formatted
*
* @return the formatted log record
*/
public String format (LogRecord record)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter (sw);
String loggerName = record.getLoggerName();
Throwable ex = record.getThrown();
String message = super.formatMessage (record);
pw.print (DATE_FORMAT.format (new Date (record.getMillis())));
pw.print (' ');
pw.print (record.getLevel().toString());
pw.print (" (");
// Logger name is a class name. Strip all but the last part of it.
int i = loggerName.lastIndexOf (".");
if ((i != -1) && (i < (loggerName.length() - 1)))
loggerName = loggerName.substring (i + 1);
pw.print (loggerName);
pw.print (") ");
if ((message != null) && (message.trim().length() > 0))
pw.println (message);
if (ex != null)
ex.printStackTrace (pw);
return sw.toString();
}
@Override
public String format(LogRecord record) {
String logger = record.getLoggerName();
if (logger.indexOf('.') >= 0) {
String caller = logger.substring(logger.lastIndexOf('.') + 1, logger.length());
return caller + ": " + record.getMessage() + "\n";
} else {
return logger + ": " + record.getMessage() + "\n";
}
}
@Override
public String format(final LogRecord record) {
final Date date = this.date.get();
date.setTime(record.getMillis());
String source;
final String sourceClassName = record.getSourceClassName();
final String sourceMethodName = record.getSourceMethodName();
if (sourceClassName != null) {
source = sourceClassName;
if (sourceMethodName != null) {
source += " " + sourceMethodName;
}
} else {
source = record.getLoggerName();
}
final String message = formatMessage(record);
String throwable = "";
final Throwable thrown = record.getThrown();
if (thrown != null) {
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
pw.println();
thrown.printStackTrace(pw);
pw.close();
throwable = sw.toString();
}
return String.format(
locale, format,
date, source,
record.getLoggerName(),
Locale.ENGLISH == locale ? record.getLevel().getName() : record.getLevel().getLocalizedName(),
message, throwable,
sourceClassName == null ? source : sourceClassName,
sourceMethodName == null ? source : sourceMethodName);
}
@Override
public String format(LogRecord record) {
// Add an extra newline before the message. Stackdriver does not show newlines correctly, and
// treats them as whitespace. If you want to see correctly formatted log message, expand the
// log and look for the jsonPayload.message field. This newline makes sure that the entire
// message starts on its own line, so that indentation within the message is correct.
String message = "\n" + record.getMessage();
String severity = severityFor(record.getLevel());
// The rest is mostly lifted from java.util.logging.SimpleFormatter.
String stacktrace = "";
if (record.getThrown() != null) {
StringWriter sw = new StringWriter();
try (PrintWriter pw = new PrintWriter(sw)) {
pw.println();
record.getThrown().printStackTrace(pw);
}
stacktrace = sw.toString();
}
String source;
if (record.getSourceClassName() != null) {
source = record.getSourceClassName();
if (record.getSourceMethodName() != null) {
source += " " + record.getSourceMethodName();
}
} else {
source = record.getLoggerName();
}
return gson.toJson(
ImmutableMap.of(SEVERITY, severity, SOURCE, source, MESSAGE, message + stacktrace))
+ '\n';
}
public static String getAgName(LogRecord l) {
String lname = l.getLoggerName();
int posd = lname.lastIndexOf('.');
if (posd > 0) {
return lname.substring(posd+1);
}
return lname;
}
/**
* Return the log4j-Logger instance that will be used for logging.
* Handles null name case and appends configured suffix.
*/
private org.apache.logging.log4j.Logger getLog4jLogger(LogRecord record) {
String name = record.getLoggerName();
if (name == null) {
name = UNKNOWN_LOGGER_NAME;
} else if (julSuffixToAppend != null) {
name += julSuffixToAppend;
}
return org.apache.logging.log4j.LogManager.getLogger(name);
}
public String format(LogRecord r) {
StringBuilder sbuf = new StringBuilder(300); // initial guess
String levelName = LogLevel.getVespaLogLevel(r.getLevel()).toString().toLowerCase();
String component = r.getLoggerName();
// format the time
sbuf.append(VespaFormat.formatTime(r.getInstant()));
sbuf.append("\t");
sbuf.append(hostname).append("\t")
.append(processID).append("/")
.append(r.getThreadID()).append("\t")
.append(serviceName).append("\t");
if (component == null && componentPrefix == null) {
sbuf.append("-");
} else if (component == null) {
sbuf.append(componentPrefix);
} else if (componentPrefix == null) {
sbuf.append(".").append(component);
} else {
sbuf.append(componentPrefix).append(".").append(component);
}
sbuf.append("\t").append(levelName).append("\t");
// for events, there is no ordinary message string;
// instead we render a string represantion of the event object:
if (r.getLevel() == LogLevel.EVENT) {
Event event = (Event) r.getParameters()[0];
sbuf.append(VespaFormat.escape(event.toString()));
} else {
// otherwise, run standard java text formatting on the message
sbuf.append(VespaFormat.escape(formatMessage(r)));
}
appendException(r.getThrown(), sbuf);
sbuf.append("\n");
return sbuf.toString();
}
@Override
public String format(LogRecord record) {
Throwable t=record.getThrown();
int level=record.getLevel().intValue();
String name=record.getLoggerName();
long time=record.getMillis();
String message=formatMessage(record);
if( name.indexOf('.') >= 0 )
name = name.substring(name.lastIndexOf('.') + 1);
// Use a string buffer for better performance
StringBuilder buf = new StringBuilder();
buf.append(time);
// pad to 8 to make it more readable
for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }
// Append a readable representation of the log level.
switch(level) {
case LOG_LEVEL_TRACE: buf.append(" T "); break;
case LOG_LEVEL_DEBUG: buf.append(" D "); break;
case LOG_LEVEL_INFO: buf.append(" I "); break;
case LOG_LEVEL_WARN: buf.append(" W "); break;
case LOG_LEVEL_ERROR: buf.append(" E "); break;
//case : buf.append(" F "); break;
default: buf.append(" ");
}
// Append the name of the log instance if so configured
buf.append(name);
buf.append(" ");
// pad to 20 chars
for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }
// Append the message
buf.append(message);
// Append stack trace if not null
if(t != null) {
buf.append(System.lineSeparator());
java.io.StringWriter sw= new java.io.StringWriter(1024);
java.io.PrintWriter pw= new java.io.PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
buf.append(sw.toString());
}
buf.append(System.lineSeparator());
// Print to the appropriate destination
return buf.toString();
}
@Override
public void publish(LogRecord record) {
try {
int level = getAndroidLevel(record.getLevel());
String tag = record.getLoggerName();
if (tag == null) {
// Anonymous logger.
tag = "null";
} else {
// Tags must be <= 23 characters.
int length = tag.length();
if (length > 23) {
// Most loggers use the full class name. Try dropping the
// package.
int lastPeriod = tag.lastIndexOf(".");
if (length - lastPeriod - 1 <= 23) {
tag = tag.substring(lastPeriod + 1);
} else {
// Use last 23 chars.
tag = tag.substring(tag.length() - 23);
}
}
}
/* ############################################################################################
Instead of using the perfectly fine java.util.logging API for setting the
loggable levels, this call relies on a totally obscure "local.prop" file which you have to place on
your device. By default, if you do not have that file and if you do not execute some magic
"setprop" commands on your device, only INFO/WARN/ERROR is loggable. So whatever you do with
java.util.logging.Logger.setLevel(...) doesn't have any effect. The debug messages might arrive
here but they are dropped because you _also_ have to set the Android internal logging level with
the aforementioned magic switches.
Also, consider that you have to understand how a JUL logger name is mapped to the "tag" of
the Android log. Basically, the whole cutting and cropping procedure above is what you have to
memorize if you want to log with JUL and configure Android for debug output.
I actually admire the pure evil of this setup, even Mr. Ceki can learn something!
Commenting out these lines makes it all work as expected:
if (!Log.isLoggable(tag, level)) {
return;
}
############################################################################################### */
String message = getFormatter().format(record);
Log.println(level, tag, message);
} catch (RuntimeException e) {
Log.e("AndroidHandler", "Error logging message.", e);
}
}
@Override
public String format(LogRecord record) {
Throwable t=record.getThrown();
int level=record.getLevel().intValue();
String name=record.getLoggerName();
long time=record.getMillis();
String message=formatMessage(record);
if( name.indexOf('.') >= 0 )
name = name.substring(name.lastIndexOf('.') + 1);
// Use a string buffer for better performance
StringBuilder buf = new StringBuilder();
buf.append(time);
// pad to 8 to make it more readable
for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }
// Append a readable representation of the log level.
switch(level) {
case LOG_LEVEL_TRACE: buf.append(" T "); break;
case LOG_LEVEL_DEBUG: buf.append(" D "); break;
case LOG_LEVEL_INFO: buf.append(" I "); break;
case LOG_LEVEL_WARN: buf.append(" W "); break;
case LOG_LEVEL_ERROR: buf.append(" E "); break;
//case : buf.append(" F "); break;
default: buf.append(" ");
}
// Append the name of the log instance if so configured
buf.append(name);
buf.append(" ");
// pad to 20 chars
for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }
// Append the message
buf.append(message);
// Append stack trace if not null
if(t != null) {
buf.append(LINE_SEP);
java.io.StringWriter sw= new java.io.StringWriter(1024);
java.io.PrintWriter pw= new java.io.PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
buf.append(sw.toString());
}
buf.append(LINE_SEP);
// Print to the appropriate destination
return buf.toString();
}
private boolean isBlacklisted(LogRecord record) {
// Guava futures internals are not very actionable to the user but we still want to have
// them in the log.
return record.getLoggerName() != null
&& record.getLoggerName().startsWith("com.google.common.util.concurrent");
}
@Override
public String format(LogRecord record) {
Throwable t=record.getThrown();
int level=record.getLevel().intValue();
String name=record.getLoggerName();
long time=record.getMillis();
String message=formatMessage(record);
if( name.indexOf('.') >= 0 )
name = name.substring(name.lastIndexOf('.') + 1);
// Use a string buffer for better performance
StringBuilder buf = new StringBuilder();
buf.append(time);
// pad to 8 to make it more readable
for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }
// Append a readable representation of the log level.
switch(level) {
case LOG_LEVEL_TRACE: buf.append(" T "); break;
case LOG_LEVEL_DEBUG: buf.append(" D "); break;
case LOG_LEVEL_INFO: buf.append(" I "); break;
case LOG_LEVEL_WARN: buf.append(" W "); break;
case LOG_LEVEL_ERROR: buf.append(" E "); break;
//case : buf.append(" F "); break;
default: buf.append(" ");
}
// Append the name of the log instance if so configured
buf.append(name);
buf.append(" ");
// pad to 20 chars
for( int i=0; i<8-buf.length(); i++ ) { buf.append(" "); }
// Append the message
buf.append(message);
// Append stack trace if not null
if(t != null) {
buf.append(LINE_SEP);
java.io.StringWriter sw= new java.io.StringWriter(1024);
java.io.PrintWriter pw= new java.io.PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
buf.append(sw.toString());
}
buf.append(LINE_SEP);
// Print to the appropriate destination
return buf.toString();
}
/**
* Reports a warning described by the given log record. The default implementation forwards
* the given record to one of the following destinations, in preference order:
*
* <ul>
* <li><code>{@linkplain StoreListener#eventOccured StoreListener.eventOccured}(new
* {@linkplain WarningEvent}(source, record))</code> on all listeners registered for this kind of event.</li>
* <li>Only if above step found no listener, then <code>{@linkplain Logging#getLogger(String)
* Logging.getLogger}(record.loggerName).{@linkplain Logger#log(LogRecord) log}(record)</code>
* where {@code loggerName} is one of the following:
* <ul>
* <li><code>record.{@linkplain LogRecord#getLoggerName() getLoggerName()}</code> if that value is non-null.</li>
* <li>Otherwise the value of {@link DataStoreProvider#getLogger()} if the provider is found.</li>
* <li>Otherwise the source {@link DataStore} package name.</li>
* </ul>
* </li>
* </ul>
*
* @param description warning details provided as a log record.
*/
@SuppressWarnings("unchecked")
public void warning(final LogRecord description) {
if (!fire(new WarningEvent(source, description), WarningEvent.class)) {
final String name = description.getLoggerName();
final Logger logger;
if (name != null) {
logger = Logging.getLogger(name);
} else {
logger = getLogger();
description.setLoggerName(logger.getName());
}
if (description instanceof QuietLogRecord) {
((QuietLogRecord) description).clearImplicitThrown();
}
logger.log(description);
}
}
@Override
public String getLoggerName(LogRecord res) {
return res.getLoggerName();
}