java 使用 slf4j Logger 记录所有 HashMap 键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44339281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:07:05  来源:igfitidea点击:

Log all HashMap keys and values using slf4j Logger

javaloggingslf4j

提问by My Intek

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

如何使用 slf4j 记录器记录 HashMap 键和值。我已经尝试了几次,但仍然想通了。

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);
  }

回答by Stephen C

Your code is using this overload (see javadoc)

您的代码正在使用此重载(请参阅javadoc

void info(String message, Object p0)

Logs a message with parameters at info level.

void info(String message, Object p0)

在信息级别记录带有参数的消息。

That overload will substitutethe string representation of p0into the messagetemplate string, replacing the first substitution marker with the representation. But you don't have any substitution markers in your message!

即超载将替代的字符串表示p0message模板字符串,与表示更换第一替代标记。但是您的消息中没有任何替换标记!

Here is a quick fix:

这是一个快速修复:

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

Related Question:

相关问题:

回答by Rajith Pemabandu

Suppose you try like this to iterate in the HashMap.

假设您尝试像这样在 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.

这篇文章中有更多的例子和方法。