2

How do you dynamically pick a log message level when using SLF4J? Is it possible? I would like to avoid writing code like

String message = "message";
if (someCondition) {
    log.info(message);
} else if (someOtherCondition) {
    log.warn(message);
} // and potentially even more ifs

This would be better (the code is made-up, such methods don't actually exist)

String message = "message";
log.log(message, levelProvider::getLoggingLevel);

Please note this question is not about setting a logging level of the entire logger

JoreJoh
  • 113
  • 5
  • It's a strange use case. Usually when the condition makes a higher log level necessary, you would also want to change the message. It's a different thing that happens, after all. – Jorn Aug 28 '23 at 08:32

1 Answers1

3

I think you want to use Logger.atLevel(Level) to get a LoggingEventBuilder. You can then call log(String) on that. Like,

logger.atLevel(levelProvider.getLoggingLevel()).log(message);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249