问题
We are using java.util.logging
void log(Level level, Throwable thrown, Supplier<String> msgSupplier)
and a few more convenience methods like
logp(Level level, String sourceClass, String sourceMethod,
String msg, Object params[])
But no varargs method. How come? Does this seem like a future enhancement or is there any good reason not to have something like :
public void log( Level level, Throwable t, String msg, Object... params) {
// throw new RuntimeException("No yet impl");
if (!isLoggable(level)) {
return;
}
LogRecord lr = new LogRecord(level, msg);
lr.setParameters(params);
if (t != null) {
lr.setThrown(t);
}
doLog(lr);
}
I created helper :
public static void log(Logger logger, Level level, Throwable t, String msg, Object... params) {
// throw new RuntimeException("No yet impl");
if (!logger.isLoggable(level)) {
return;
}
LogRecord lr = new LogRecord(level, msg);
lr.setParameters(params);
if (t != null) {
lr.setThrown(t);
}
logger.log(lr);
}
would loved to have called doLog instead of log in the last line, but doLog is a private helper! Not sure why, as there is no way for me to set the bundle etc - wish it was
public void doLog(LogRecord lr) instead of private.
Anyway, for us to do the same things the following method does so that we can use our own varargs method?
// resource bundle and then call "void log(LogRecord)".
private void doLog(LogRecord lr) {
lr.setLoggerName(name);
final LoggerBundle lb = getEffectiveLoggerBundle();
final ResourceBundle bundle = lb.userBundle;
final String ebname = lb.resourceBundleName;
if (ebname != null && bundle != null) {
lr.setResourceBundleName(ebname);
lr.setResourceBundle(bundle);
}
log(lr);
}
回答1:
But no varargs method. How come? Does this seem like a future enhancement...
There are multiple requests for Use varargs in java.util.logging.Logger on the OpenJDK site over the years. The API wasn't really maintained after JDK 5. Logging was updated in JDK 8 for Lambda Expressions but the logging guide wasn't updated for best practices just a few examples in the java.util.logging.Logger.
I created helper
public static void log(Logger logger, Level level, Throwable t, String msg, Object... params)
You might want to use the version in How can I log with params with a thrown? as it will retain the correct class and method name because the caller is still responsible for publishing the log record.
is there any good reason not to have something like
log(Level level, Throwable t, String msg, Object... params)
It is probably safe addition. Oracle ran a survey and it is clear they would prefer you to use a lambda or method reference with one of the log methods that takes a Supplier<String>
and lean on the java.util.Formatter providing the supporting for var-args.
} catch (IllegalArgumentException iae) {
logger.log(Level.SEVERE, iae, () -> String.format("%1$s is too many.", count));
}
Sugary sweet lambda syntax over vegetables!
来源:https://stackoverflow.com/questions/44185698/varargs-in-java-util-logging-java-8