How can I use apache commons cli with log4j?

I can write this kind of code with apache commons cli:

HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("myapp", options, true);

This will print all the command line options and their description.

I want to print this using a logger, like log4j, but I don't know how, there's only the printHelp function in the HelpFormatter class.

I don't want to over-engineer anything, is there a standard way of doing this?

728x90

1 Answers How can I use apache commons cli with log4j?

Use one of the two printHelp methods that takes a PrintWriter as the first argument, give it a PrintWriter wrapping a StringWriter, then give the result to whichever logging API you want to use.

Example

try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
    HelpFormatter f = new HelpFormatter();
    f.printHelp(pw, f.getWidth(), "myapp", null, options,
                f.getLeftPadding(), f.getDescPadding(), null, true);
    pw.flush();
    logger.info(sw.toString());
}

5 months ago