Here's what I'm looking for:
- Java
- Log library that could replace commons logging or slf4j
- Parameter expansion only when log level requires it (i.e. no
if (log.isDebugEnabled())
blocks) - String formatting the same as
java.lang.String.format
- Detect java.lang.Throwable as final parameter and log stack trace
The goal is to write code like this
private static final Log log = new Log.getLog(MyClass.class);
// ...
String value = "test";
log.debug("The value is [%s]", value); // [1]
// ...
} catch (Exception e) {
log.error("Caught Exception: %s", e.getMessage(), e); // [2]
}
[1] would print a log statement like
The value is [test]
If the log level were INFO
, the string format operation would not happen.
[2] would print
Caught Exception: [value of e.getMessage()]
java.lang.Exception
at com.my.org.MyClass.myMethod(MyClass.[line number])
at [...]
This seems like pretty sane behavior to me. I'm surprised 开发者_JAVA百科I can't easily find a library that does this.
EDIT: I should have specified, but slf4j does not meet all these requirements.
Java
SLF4J with Logback binding.
Log library that could replace commons logging or slf4j
The only well established alternatives are Log4J and java.util.logging
...
Parameter expansion only when log level requires it (i.e. no if (log.isDebugEnabled()) blocks)
In SLF4J if you type:
log.debug("Names are: {}", namesCollection);
Then costly toString()
will only be executed if isDebugEnabled()
returns true (no need to provide it explicitly).
String formatting the same as java.lang.String.format
Do you really need fancy formatting (decimals, currencies, locales) in log files? Or is {}
lazy expansion enough (see above)?
Detect java.lang.Throwable as final parameter and log stack trace
SLF4J works this way since 1.6.
JBoss has a logging implementation that does printf- and MessageFormat-style formatting. Supposedly it can be used on it's own, but I can't find a project for it, other than its integration with Seam Solder. There are standalone artifacts though: https://repository.jboss.org/nexus/content/groups/public/org/jboss/logging/jboss-logging/
精彩评论