4

How can I log HashMap keys and values using slf4j logger. I've trying this a couple of times but still figured out.

The following code just only logs the "test values" string without the values of maps arguments.

  public void test(HashMap maps) {
      logger.info("test values", maps);
  }
My Intek
  • 85
  • 1
  • 2
  • 5

2 Answers2

14

Your code is using this overload (see javadoc)

void info(String message, Object p0)

Logs a message with parameters at info level.

That overload will substitute the string representation of p0 into the message template string, replacing the first substitution marker with the representation. But you don't have any substitution markers in your message!

Here is a quick fix:

  public void test(HashMap maps) {
      logger.info("test values {}", maps);
  }

Related Question:

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

Suppose you try like this to iterate in the HashMap.

public void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        logger.info(pair.getKey() + " = " + pair.getValue());
    }
}

There are more examples and approaches in this post.

Rajith Pemabandu
  • 616
  • 7
  • 14