使用java.util.logging.Logger,如何记录参数并抛出异常?
java.util.logging.Logger
final Object[] params; final Throwable thrown;
我找不到任何方法log(Level, String, Object[], Throwable)。
log(Level, String, Object[], Throwable)
我应该使用log(Level, String.format(...), Throwable)还是log(Level, Throwable, () -> String.format(...))?
log(Level, String.format(...), Throwable)还是log(Level, Throwable, () -> String.format(...))
有没有办法把两者String并Object[]以java.util.logging.Logger中。
String并Object[]
我会转换String[]为String并使用:
String[]
String
public void log(Level level, String msg, Throwable thrown)
您还可以创建log指向的自己的方法,java.util.logging.Logger.log例如:
java.util.logging.Logger.log
public void log(Level level, String msg, Object[] obj, Throwable thrown) { //StringBuilder buff = ... // some string manipulation with 'msg' and 'obj' // ... log(level, buff.toString(), thrown); }
总体看来,JUL正在向迈进log(Level, Throwable, () -> String.format(msg, params))。但是,这不使用日志记录参数数组,该数组具有一些带有过滤器的实用程序。
另一种选择是创建一个辅助方法来构造日志记录,并让调用者对其进行记录:
public class ThrownWithParams { private static final Logger logger = Logger.getLogger("test"); public static final void main(String[] args) { logger.log(of(logger, Level.SEVERE, new Exception("Fake"), "Test {0}, {1}", "FOO", "BAR")); } private static LogRecord of(Logger l, Level v, Throwable t, String m, Object... p) { //Let the caller invoke get/setSourceClassName or get/setSourceMethodName. LogRecord r = new LogRecord(v, m); r.setLoggerName(l.getName()); r.setResourceBundleName(l.getResourceBundleName()); r.setResourceBundle(l.getResourceBundle()); r.setParameters(p); r.setThrown(t); return r; } }
这是理想的,因为调用者记录了该记录,这意味着推断出的源方法和源类名称将是正确的。