Log all HashMap keys and values using slf4j Logger

21,753

Solution 1

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:

Solution 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.

Share:
21,753
My Intek
Author by

My Intek

Updated on June 03, 2020

Comments

  • My Intek
    My Intek almost 4 years

    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
    My Intek almost 7 years
    I only want to log all the keys and values once not one log per key and value pair.