2

I have built a Java command-line tool that uses SLF4J (the simple binding) for logging. Throughout its codebase I have many different INFO, TRACE, WARN and ERROR statements. Normally, when users run this tool, I would like it to only log INFO and above (so: INFO, WARN and ERROR). However, I would like users to be able to supply a --verbose (or -v) option at the command-line, and have TRACE messages get logged as well.

To reiterate, normal command-line invocation:

java -jar mytool.jar --fizz "30" --buzz "true"

But in "verbose mode":

java -jar mytool.jar --fizz "30" --buzz "true" --verbose

I know I can configure SLF4J setting from the command line like so:

java -jar -Dorg.slf4j.simpleLogger.defaultLogLevel "trace" mytool.jar --fizz "30" --buzz "true"

But this isn't as user friendly, and it also "leaks" the fact that SLF4J is the underlying logging system to the end user. Not that I'm worried about security, it just feels like a less-than-elegant config solution. IMHO, the end user of this tool shouldn't have to know any implementation details about the tool in order to run it, especially what a TRACE log level means or represents.

Any ideas?

smeeb
  • 27,777
  • 57
  • 250
  • 447

1 Answers1

1

How about you check whether the --verbose option exists and do System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");?

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • Thanks @Kayaman (+1) - I see in the SLF4J API there are `isXYZEnabled()` methods on the loggers. Are there any respective setters that you know of (for instance, `setTraceEnabled(true)`, etc.? Or are these all keyed off of the system property that you just provided in your code example? Thanks again! – smeeb Jun 30 '15 at 14:14
  • 1
    No there's no setters for them. They're used to check whether a specific level is enabled in case something heavy needs to be done for logging (i.e. for example if you build a large String for debug, but don't want to build the String in case the level isn't enabled). – Kayaman Jun 30 '15 at 14:23
  • This won't work with slf4j simpleLogger. Because the log level can't be changed after simpleLogger has been initialized. See: http://stackoverflow.com/a/16887899/972759 – VolkerK Mar 29 '16 at 14:13