java - 使用 SimpleFormatter 限制字符串长度

标签 java logging java.util.logging

我正在尝试限制 SimpleFormatter 格式的源参数的长度,以便在 Tomcat 8 中使用。

我已阅读SimpleFormatter docFormatter syntax doc虽然我不会假装我已经理解了第二个,但在论证后面加上一个数字应该会限制它的长度。

但在我的测试中却没有:

输出的行

java.util.logging.SimpleFormatter.format = %4$s %n

java.util.logging.SimpleFormatter.format =%4$1s %n

难以区分。

我错过了什么吗?

最佳答案

I'm trying to limit the length of the source parameter in a SimpleFormatter format, to use in Tomcat 8.

由于您只需要级别的第一个字符,因此语法为 %4$.1s

根据 java.util.Formatter JavaDocs :

The format specifiers for general, character, and numeric types have the following syntax:

   %[argument_index$][flags][width][.precision]conversion

The optional width is a positive decimal integer indicating the minimum number of characters to be written to the output.

The optional precision is a non-negative decimal integer usually used to restrict the number of characters.

这意味着使用点字符指定精度。由于您不关心最大值,如果最小值为零,那么您必须从模式中忽略它。

以下是构建模式的示例测试用例:

public static void main(String[] args) {
    //This really should be set as a command argument but, it works.

    //No min and max of seven chars of level.
    //System.setProperty("java.util.logging.SimpleFormatter.format", "%4$.7s %n");

    //Min and max of seven chars of level (right justified).
    //System.setProperty("java.util.logging.SimpleFormatter.format", "%4$7.7s %n");

    //Min and max of seven chars of level (left justified).
    //System.setProperty("java.util.logging.SimpleFormatter.format", "%4$-7.7s %n");

    //No min with max of one chars of level.
    System.setProperty("java.util.logging.SimpleFormatter.format", "%4$.1s %n");

    LogRecord r = new LogRecord(Level.SEVERE, "Message");
    r.setLoggerName("logger");
    r.setSourceClassName("class");
    r.setSourceMethodName("method");
    System.out.println(new SimpleFormatter().format(r));
}

JavaDocs 还指出:

For character, integral, and date/time argument types and the percent and line separator conversions, the precision is not applicable; if a precision is provided, an exception will be thrown.

文档实际上应该说“参数类别”,而不是“参数类型”。在参数类别表中,“s”和“S”被视为“常规”而不是“字符”。这就是为什么您可以使用点精度。

关于java - 使用 SimpleFormatter 限制字符串长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35745714/

相关文章:

java - 如何让记录器包裹在 slf4j 中?

java - 使用 <ant> 任务调用的构建文件会重置调用者的日志记录配置

java - 为什么我的 JFrame 不更新

java - 如何在 Vuforia SDK 中使用 jPCT?

logging - 使用Firebase托管时可以访问w3c样式日志吗

logging - symfony 中的多个日志文件

java - Netbeans 无法安装在 MacOS Big Sur 上

java - 如何部分更新spring缓存(仅一个字段)?(当对象发生变化时)

java - 套接字将多个客户端编程到一台服务器

eclipse - 2015 年登录 Java - 正确配置的环境是什么样的?