使用 SimpleFormatter 限制字符串长度

Limiting String length with SimpleFormatter

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

中使用

我已经阅读了 SimpleFormatter doc and the Formatter syntax doc 虽然我不会假装我已经理解了第二个,但是在参数后面的数字应该会限制它的长度。

但我的测试中没有:

输出的行

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

java.util.logging.SimpleFormatter.format =%4s %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.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.

而不是 'argument types' 文档实际上应该说 'argument category'。 's' 和 'S' 在参数类别 table 中被视为 'general' 而不是 'character'。这就是您可以使用点精度的原因。