Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing an array with slf4j only prints the first element

Tags:

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?

like image 289
Pavel_K Avatar asked Sep 20 '16 09:09

Pavel_K


People also ask

How do you print out an array of elements?

We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.

How do I print an array of elements in one line?

Print Array in One Line with Java StreamsArrays. toString() and Arrays. toDeepString() just print the contents in a fixed manner and were added as convenience methods that remove the need for you to create a manual for loop.

What is the advantage of SLF4J?

This is the main purpose of SLF4J (Simple Logging Facade for Java) – a logging abstraction which helps to decouple your application from the underlying logger by allowing it to be plugged in – at runtime. Of course, the flexibility that such an abstraction provides is the main reason to use SLF4J.

What logger does SLF4J use?

SLF4J supports popular logging frameworks, namely log4j, java. util. logging, Simple logging and NOP. The logback project supports SLF4J natively.


1 Answers

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.

like image 171
Tunaki Avatar answered Nov 28 '22 10:11

Tunaki