When using log4j, the Logger.log(Priority p, Object message)
method is available and can be used to log a message at a log level determined at runtime. We're using this fact and this tip to redirect stderr to a logger at a specific log level.
slf4j doesn't have a generic log()
method that I can find. Does that mean there's no way to implement the above?
I was able to do this for the JDK14 binding by first requesting the SLF4J Logger instance and then setting the level on the binding -- you may try this for the Log4J binding.
Here's a lambda solution not as user-friendly as @Paul Croarkin's in one way (the level is effectively passed twice). But I think (a) the user should pass the Logger; and (b) AFAIU the original question was not asking for a convenient way for everywhere in the application, only a situation with few usages inside a library.
Since slf4j allows a Throwable (whose stack trace should be logged) inside the varargs param, I think there is no need for overloading the
log
helper method for other consumers than(String, Object[])
.using java introspection you can do it, for example:
I have just encountered a similar need. In my case, slf4j is configured with the java logging adapter (the jdk14 one). Using the following code snippet I have managed to change the debug level at runtime:
This can be done with an
enum
and a helper method:You could add other variants of
log
, say if you wanted generic equivalents of SLF4J's 1-parameter or 2-parameterwarn
/error
/etc. methods.Based on the answer of massimo virgilio, I've also managed to do it with slf4j-log4j using introspection. HTH.