2016-12-18 64 views
2

With java.util.logging.Logger,如何使用params和拋出的日誌記錄?如何使用拋出的參數記錄日誌?

final Object[] params; 
final Throwable thrown; 

我找不到任何方法與log(Level, String, Object[], Throwable)

我應該使用log(Level, String.format(...), Throwable)還是log(Level, Throwable,() -> String.format(...))

回答

2

無法將StringObject[]設置爲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); 
} 
2

一般來說它看起來像JUL正在向log(Level, Throwable,() -> String.format(msg, params))移動。但是,這不使用log record parameters array,它具有一些過濾器的實用程序。

另一種選擇是創建一個輔助方法construct the log record,讓來電者log it

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; 
    } 
} 

這是理想的,因爲來電記錄,這意味着推斷源法和源類的名稱將是正確的記錄。

相關問題