[英]How can I log with params with a thrown?
使用java.util.logging.Logger
,如何記錄params和throw?
final Object[] params;
final Throwable thrown;
我找不到任何帶有log(Level, String, Object[], Throwable)
。
我應該使用log(Level, String.format(...), Throwable)
還是log(Level, Throwable, () -> String.format(...))
?
無法將String
和Object[]
都放置到java.util.logging.Logger中 。
我將String[]
轉換為String
並使用:
public void log(Level level,
String msg,
Throwable thrown)
您還可以創建自己的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;
}
}
這是理想的,因為調用者記錄了該記錄,這意味着推斷出的源方法和源類名稱將是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.