28

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?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Pavel_K
  • 10,748
  • 13
  • 73
  • 186
  • 2
    @JimJim2000 The way you're printing the array is fine, slf4j (if backed by log4j, logback or any other implementation) will output the contents of the array. Therefore, you'll need to tell us what "does not work" exactly means. Do you see any slf4j messages? Any output? Are you aware that the [`String#split()`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-) method you're calling accepts a regex, and that ".." is a regex that has a meaning? – Petr Janeček Sep 20 '16 at 09:22

2 Answers2

59

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.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
-2

I am facing a strange issue where the entire list of arguments is logged for the first place holder eg: log.info("Initializing Service. arg1={}, arg2={}, pid={}", arg1, arg2, arg3);

logs the following: Initializing Service. build=[123456, main, 77378], branch=null, pid={}

Sreeja Mohan
  • 135
  • 2
  • 6