-
Notifications
You must be signed in to change notification settings - Fork 425
Configuring Logging in a CLI App
Remko Popma edited this page Feb 7, 2020
·
2 revisions
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import picocli.CommandLine;
import picocli.CommandLine.Option;
class MyApp {
private static Logger logger = LogManager.getLogger(MyApp.class);
@Option(names = {"-v", "--verbose"},
description = {
"Specify multiple -v options to increase verbosity.",
"For example, `-v -v -v` or `-vvv`"})
boolean[] verbosity = new boolean[0];
private void configureLoggers() {
if (verbosity.length >= 3) {
Configurator.setRootLevel(Level.TRACE);
} else if (verbosity.length == 2) {
Configurator.setRootLevel(Level.DEBUG);
} else if (verbosity.length == 1) {
Configurator.setRootLevel(Level.INFO);
} else {
Configurator.setRootLevel(Level.WARN);
}
}
@Override
public void run() {
logger.trace("Starting... (trace)");
logger.debug("Starting... (debug)");
logger.info("Starting... (info)");
logger.warn("Starting... (warn)");
}
public static void main(String[] args) {
System.exit(new CommandLine(new MyApp())
.setExecutionStrategy(parseResult -> {
MyApp app = parseResult.commandSpec().commandLine().getCommand();
app.configureLoggers();
return new CommandLine.RunLast().execute(parseResult);
}).execute(args));
}
}