我正在尝试限制 SimpleFormatter 格式的源参数的长度,以便在 Tomcat 8 中使用。
我已阅读SimpleFormatter doc和 Formatter 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/