4.5.5.3. 使用参数自定义日志消息
自定义日志记录方法可以定义参数。这些参数用于传递要在日志消息中显示的其他信息。在日志消息中出现参数时,使用显式或普通索引方式在消息本身中指定。
使用参数自定义日志消息
- 向方法定义中添加任何类型的参数。无论类型如何,参数的 String 表示法就是消息中显示的内容。
添加对该日志消息的参数引用。参考可以使用显式或普通索引。
-
要使用普通索引,请在您希望显示每个参数的消息字符串中插入
%s字符。%s的第一个实例将插入第一个参数,第二个实例将插入第二个参数,以此类推。 -
要使用显式索引,请在消息中插入
%#$s字符,其中 # 代表您要显示的参数数。
-
要使用普通索引,请在您希望显示每个参数的消息字符串中插入
使用显式索引时,消息中的参数引用的顺序与方法中定义的不同顺序不同。这对于可能需要对参数进行不同排序的转换消息来说非常重要。
重要
参数数量必须与指定消息中参数的引用数量匹配,否则代码不会编译。标有 @Cause 注释的参数 不包含在参数数中。
以下是使用普通索引的消息参数示例:
@LogMessage(level=Logger.Level.DEBUG) @Message(id=2, value="Customer query failed, customerid:%s, user:%s") void customerLookupFailed(Long customerid, String username);
@LogMessage(level=Logger.Level.DEBUG)
@Message(id=2, value="Customer query failed, customerid:%s, user:%s")
void customerLookupFailed(Long customerid, String username);
以下是使用显式索引的消息参数示例:
@LogMessage(level=Logger.Level.DEBUG) @Message(id=2, value="Customer query failed, user:%2$s, customerid:%1$s") void customerLookupFailed(Long customerid, String username);
@LogMessage(level=Logger.Level.DEBUG)
@Message(id=2, value="Customer query failed, user:%2$s, customerid:%1$s")
void customerLookupFailed(Long customerid, String username);