Setting log level of message at runtime in slf4j Ask Question

Setting log level of message at runtime in slf4j Ask Question

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?

Update: As of SLF4J version 2.0, it is possible to use the Logger.atLevel() method. For example:

import org.slf4j.event.Level;
import org.slf4j.Logger;
...
Logger logger = ... // some slf4j logger of choice
logger.atLevel(Level.Info).log("hello world");

ベストアンサー1

There is no way to do this with slf4j 1.x.

I imagine that the reason that this functionality is missing is that it is next to impossible to construct a Level type for slf4j that can be efficiently mapped to the Level (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.


UPDATE

They intend to implement piecemeal construction of logging events (with dynamic logging levels) in slf4j 2.0; see https://jira.qos.ch/browse/SLF4J-124. According to @Ceki (see comments), it is implemented in the 2.0.0-alpha2 release.

おすすめ記事