在我们的域中,我们为日志消息提供了结构化参数,以便描述对象ID。例如,如果对象SomeObject有三个ID字段用于标识该对象:
class SomeObject {
SomeObjectId id;
....
}
class SomeObjectId {
LocalDate date;
int objectId;
String objectLocation;
}
我们使用以下日志设置来记录所有ID字段:
import static net.logstash.logback.argumentStructuredArgument.v;
log.info("Some object with ID {} {} {} is processed on {}.",
v("date", objectId.getDate()),
v("objectId", objectId.getObjectId()),
v("location", objectId.getObjectLocation()),
"someOtherArgument" // etc
);
生成以下JSON日志输出:
{
"@timestamp": "2022-11-30T12:34:56.000+00:00",
"@version": "1",
"message": "Some object with ID 2022-11-30 123 NL is processed on someOtherArgument",
"thread_name": "main",
"level": "INFO",
// Notice the structured arguments
"date": "2022-11-30",
"objectId": "123",
"location": "NL"
}
在代码中的每个日志部分显式地提到每个ID字段感觉有点麻烦。有没有一种方法可以将这些字段组合到日志字符串中,同时将所有结构化参数添加到日志消息中?例如(在伪代码中):
log.info("Some object with ID {} is processed on {}.",
LogTags.fromId(someObjectId),
"someOtherArgument" // etc
);
class LogTags {
static String fromId(SomeObjectId id) {
LogTags.forCurrentLogMessage.appendValue("date", id.getDate());
LogTags.forCurrentLogMessage.appendValue("objectId", id.getObjectId());
LogTags.forCurrentLogMessage.appendValue("location", id.getLocation());
return id.getDate() + " " + id.getObjectId() + " " + id.getLocation();
}
}
1条答案
按热度按时间tktrz96b1#
是,使用
StructuredArguments.fields(object)
(或其缩写形式StructuredArguments.f(object)
)例如:
第一个