Lambda support for SLF4J API

In the newest Log4j API, we have Lambda support where I can easily manage the Debug option.

Example: logger.debug("This {} and {} with {} ", () -> this, () -> that, () -> compute()); 

But for slf4j / logback, is there an option to enable lambda, as mentioned above. Please let me know the syntax.

+5
source share
3 answers

Unfortunately, this is not yet supported: https://jira.qos.ch/browse/SLF4J-371

+2
source

Perhaps something like this will work. You will need to determine if the cost of new 'instances is better than doing it differently.

 logger.debug("This {} and {} with {} ", defer(() -> this), defer(() -> that), defer(() -> compute())); 

Then with this ...

 import lombok.NonNull; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor(staticName = "defer") public class LogString { @NonNull private final StringGenerator generator; @Override public String toString() { return generator.createString(); } public interface StringGenerator { String createString(); } } 
+1
source

slf4j-lambda supports this:

 import kr.pe.kwonnam.slf4jlambda.LambdaLogger; import kr.pe.kwonnam.slf4jlambda.LambdaLoggerFactory; LambdaLogger log = LambdaLoggerFactory.getLogger(YourClass.class); // lambda for message itself log.debug(() -> createMessage("debug level")); // lambda for message format arguments log.info("info lambda formatter number {}, string {}", () -> 123, () -> "Hello LambdaLogger"); // method reference public String longRunnigMethod() { return "some long running method"; } log.debug("Long running method logging {}", this::longRunnigMethod); // exception logging log.error(() -> "error lambda exception msg - " + ex.getMessage(), ex); 
+1
source

Source: https://habr.com/ru/post/1261622/


All Articles