This question already has an answer here:
We are looking to use SLF4J, but one thing we found was that you can't specify the level as an argument, i.e
Logger.log(Level.INFO, "messsage");
You have to do this
logger.info("message");
this prevents being able to pass everything through a method, so you can tack other properties to all log messages in a class.
public class Test
{
public Test(SomeObj obj)
{
log(Level.INFO, "message");
}
public void anotherMethod()
{
log(Level.DEBUG, "another message");
}
private void log(Level level, String message)
{
logger.log(level, message + obj.someString());
}
}
Is there a way to achieve this using SLF4j ?
Well, technically SLF4J doesn't offer you a logger.log(Level, message) method. But I found a way around that. [edit: uses introspection]
Using the below code snippet you can get the native logger that slf4j found and wrapped for you at runtime. If you'll recall, slf4j is simply a wrapper around an slf4j implementation from another provider (either, jdkLogging, Log4J, JCL, etc...). So here:
Then you can use it like this:
So while it's not technically within slf4j, it is possible to do it using slf4j as your primary logging interface.
The answer is No. Refer to this discussion.
Your usecase screams for the delegation pattern. Basically you wedge your own implementation of
Logger
between your code and SLF4J and "extend" the relevant methods:This is use in the business code like this:
For optimal reusability of the
MyLogger
classSomeObj
should either useObject.toString()
or it should implement an interface whichMyLogger
can use to get the message addendum.Write a wrapper around the slf4j call and create your own enum for the six log levels. Then in your wrapper, use a switch to call the correct slf4j call.