How can I log with params with a thrown?

2019-07-11 12:51发布

With java.util.logging.Logger, how can I log with params and a thrown?

final Object[] params;
final Throwable thrown;

I can't find any method with log(Level, String, Object[], Throwable).

Should I use log(Level, String.format(...), Throwable) or log(Level, Throwable, () -> String.format(...))?

标签: java logging
2条回答
姐就是有狂的资本
2楼-- · 2019-07-11 13:34

There is no way to put both String and Object[] to java.util.logging.Logger.

I would convert String[] to String and use:

public void log(Level level,
                String msg,
                Throwable thrown)

Also you can create your own log method that points to java.util.logging.Logger.log, something like:

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);
}
查看更多
The star\"
3楼-- · 2019-07-11 13:35

In general it looks like JUL is moving towards log(Level, Throwable, () -> String.format(msg, params)). However, this doesn't use the log record parameters array which has some utility with filters.

Another option is to create a helper method to construct the log record and let the caller 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;
    }
}

This is ideal because the caller logs the record which means that the inferred source method and source class names will be correct.

查看更多
登录 后发表回答