It is not possible to specify a log level in sjf4j 1.x out of the box. But there is hope for slf4j 2.0 to fix the issue. In 2.0 it might look like this:
// POTENTIAL 2.0 SOLUTION import org.slf4j.helpers.Util; import static org.slf4j.spi.LocationAwareLogger.*; // does not work with slf4j 1.x Util.log(logger, DEBUG_INT, "hello world!");
In the meanwhile, for slf4j 1.x, you can use this workaround:
Copy this class into your classpath:
import org.slf4j.Logger; import java.util.function.Function; public enum LogLevel { TRACE(l -> l::trace, Logger::isTraceEnabled), DEBUG(l -> l::debug, Logger::isDebugEnabled), INFO(l -> l::info, Logger::isInfoEnabled), WARN(l -> l::warn, Logger::isWarnEnabled), ERROR(l -> l::error, Logger::isErrorEnabled); interface LogMethod { void log(String format, Object... arguments); } private final Function<Logger, LogMethod> logMethod; private final Function<Logger, Boolean> isEnabledMethod; LogLevel(Function<Logger, LogMethod> logMethod, Function<Logger, Boolean> isEnabledMethod) { this.logMethod = logMethod; this.isEnabledMethod = isEnabledMethod; } public LogMethod prepare(Logger logger) { return logMethod.apply(logger); } public boolean isEnabled(Logger logger) { return isEnabledMethod.apply(logger); } }
Then you can use it like this:
Logger logger = LoggerFactory.getLogger(Application.class); LogLevel level = LogLevel.ERROR; level.prepare(logger).log("It works!"); // just message, without parameter level.prepare(logger).log("Hello {}!", "world"); // with slf4j's parameter replacing try { throw new RuntimeException("Oops"); } catch (Throwable t) { level.prepare(logger).log("Exception", t); } if (level.isEnabled(logger)) { level.prepare(logger).log("logging is enabled"); }
This will output a log like this:
[main] ERROR Application - It works! [main] ERROR Application - Hello world! [main] ERROR Application - Exception java.lang.RuntimeException: Oops at Application.main(Application.java:14) [main] ERROR Application - logging is enabled
Is it worth it?
- Pro It keeps the source code location (class names, method names, line numbers will point to your code)
- Pro You can easily define variables, parameters and return types as
LogLevel - Pro Your business code stays short and easy to read, and no additional dependencies required.
The source code as minimal example is hosted on GitHub.
slf4j 2.0. jira.qos.ch/browse/SLF4J-124 See my answer for details and for a possibleslf4j 1.x-workaround.