在SLF4J中格式化浮点数

Mat*_*aun 35 java logging slf4j

我想用SLF4J格式化我的双打并浮动到一定数量的小数位.

基本上,我正在寻找String.format("%.2f", floatValue)SLF4J中相当于Java的东西.

阅读了SLF4J的文档并在谷歌上搜索我无法找到它是否具有该功能的提示.

我正在使用slf4j-api:1.7.6slf4j-jdk14:1.7.6

任何帮助深表感谢.

Isa*_*aac 24

我假设您指的是SLF4J扩展参数的惯例,例如:

float f;
...
logger.debug("My number is {}", f);
Run Code Online (Sandbox Code Playgroud)

所以,答案是否定的.从SLF4J 1.7.7开始,您要求做的事情是不可能的,因为SLF4J的扩展算法不允许自定义渲染器(例如通过Log4J可用的渲染器).

似乎值得一个功能请求.

编辑:

嗯,{}"仅支持"性能考虑,当前格式化实现优于String.format()10次. http://www.slf4j.org/faq.html#logging_performance 所以它不太可能改变

(来源)


小智 17

一个有点丑陋的解决方案可能导致创建一个临时对象

public class DelayedFormatter{
  String format;  Object[] args;

  public DelayedFormatter(String format, Object... args){
    this.format = format;  this.args = args;
  }

  public static DelayedFormatter format(String format, Object... args){
    return new DelayedFormatter(format, args);
  }

  @Override public String toString(){
    return String.format(format, args);
  }
}
Run Code Online (Sandbox Code Playgroud)

然后

import static DelayedFormatter.format;
...
logger.debug("v = {}", format("%.03f", v));
Run Code Online (Sandbox Code Playgroud)

  • 优雅的方法 (3认同)