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?
You can implement this using Java 8 lambdas.
Anyone wanting a drop-in fully SLF4J compatible solution to this problem might want to check out Lidalia SLF4J Extensions - it's on Maven Central.
Try switching to Logback and use
I believe this will be the only call to Logback and the rest of your code will remain unchanged. Logback uses SLF4J and the migration will be painless, just the xml config files will have to be changed.
Remember to set the log level back after you're done.
There is no way to do this with
slf4j
.I imagine that the reason that this functionality is missing is that it is next to impossible to construct a
Level
type forslf4j
that can be efficiently mapped to theLevel
(or equivalent) type used in all of the possible logging implementations behind the facade. Alternatively, the designers decided that your use-case is too unusual to justify the overheads of supporting it.Concerning @ripper234's use-case (unit testing), I think the pragmatic solution is modify the unit test(s) to hard-wire knowledge of what logging system is behind the slf4j facade ... when running the unit tests.
no, it has a number of methods, info(), debug(), warn(), etc (this replaces the priority field)
have a look at http://www.slf4j.org/api/org/slf4j/Logger.html for the full Logger api.
Richard Fearn has the right idea, so I wrote up the full class based on his skeleton code. It's hopefully short enough to post here. Copy & paste for enjoyment. I should probably add some magic incantation, too: "This code is released to the public domain"