15

I've using SLF4j as my logging framework, backed by log4j. My problem is that I am looking for a way to change the logging level for my logger at runtime.

I understand that slf4j does not permit this directly through its own API, and hence, I have to access the logging provider directly. Personally, I find this to be a huge deficiency in slf4j. So now my question is how can I determine programatically through slf4j which provider I am using? The biggest purpose of using slf4j is that you become provider agnostic - you can easily switch between your favourite logging system without having to recode anything. But now, if I have to make direct calls to log4j, I am losing that ability.

At the very least, I would like to be able to determine if I am using log4j as the provider and if so, then allow the user to switch log levels.

If I do LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME), the result is an instance of org.slf4j.impl.Log4jLoggerAdapter and not even org.apache.log4j.Logger (as I would have hoped/expected).

Is there any way to find this out?

Thanks, Eric

Eric B.
  • 23,425
  • 50
  • 169
  • 316

1 Answers1

13

SLF4J is designed as an abstraction for libraries, not applications (of course, you can and should still use SLF4J in your own app's logging calls, for consistency). In your own app, you choose the underlying logger framework, so it's fine to access the log4j API in the logging-config-specific parts.

No way should a library be mucking about with changing the logging config, IMHO, so it's not appropriate for it to be on the SLF4J API.

artbristol
  • 32,010
  • 5
  • 70
  • 103
  • 3
    Fair enough, if SLF4J is solely used for libraries. However, it seems to me that something so flexible in a library should also be available to use in your application. The concept of having a single API to which I can plug in any logging framework is fantastic. Additionally, more often than not part of your application ends up being refactored into a library at some point. To have to recode any references to log4j to become slf4j doesn't make sense. If SL4j was designed only for libraries (which I don't read on the slf4j site), I find that short-sighted. – Eric B. Jun 21 '12 at 19:24
  • 3
    Sorry, didn't make clear: you should definitely use SLF4J for your app's logging calls. But in the small section of your code that deals with changing the logging config, just cast the stuff to Log4J classes. If you decide to switch logging implementations, you'd have to rewrite that bit anyway. – artbristol Jun 21 '12 at 19:26
  • Agreed. Was just trying to do everything generically. I guess that just is not feasible. It's not even a question of casting - I have to make the calls using the Log4j classes directly (ie: use log4j.Logger instead of slf4j.LoggerFactory to retrieve the loggers) – Eric B. Jun 21 '12 at 19:34