Search code examples
javaslf4j

Printing an array with slf4j only prints the first element


I have the following code:

private static final Logger logger = LoggerFactory.getLogger(Some.class);
...
String[] splits=someString.split("..");
logger.info("The string was split into <{}>",splits); // prints first element

What is the right way to print the full content of an array with slf4j?


Solution

  • The issue is that with the following code

    logger.info("The string was split into <{}>", splits);
    

    you are invoking the method info(String format, Object... arguments). Note that the last argument is a varargs. Therefore, the array you pass is interpreted as each argument of the variable argument.

    However, in this case, you want to pass an array as first argument. A simple workaround is to cast it to Object.

    String[] splits = { "foo", "bar" };
    logger.info("The string was split into {}", (Object) splits);
    

    will log The string was split into [foo, bar], as expected.