【发布时间】:2021-02-27 04:44:41
【问题描述】:
我有要添加特定日志记录的方法:
@Slf4j
@Service
public class SomethingService {
public void doSomething(Something data, String comment, Integer limit) {
Long id = saveSomethingToDatabase(data, comment);
boolean sentNotification = doSomething(id);
// ...
// Log what you done.
// Variables that always have important data: data.getName(), id
// Variables that are optional: sentNotification, comment, limit
// (optional means they aren't mandatory, rarely contains essential data, often null, false or empty string).
}
}
我可以简单地记录所有:
log.info("Done something '{}' and saved (id {}, sentNotification={}) with comment '{}' and limit {}",
something.getName(), id, sentNotification, comment, limit);
// Done something 'Name of data' and saved (id 23, sentNotification=true) with comment 'Comment about something' and limit 2
但大多数时候大多数参数都是不相关的。有了上面我得到的日志如下:
// Done something 'Name of data' and saved (id 23, sentNotification=false) with comment 'null' and limit null
这使得日志难以阅读、冗长且不必要地复杂(在大多数情况下其他参数不存在)。
我想处理所有情况,只保留基本数据。例子:
// Done something 'Name of data' and saved (id 23)
// Done something 'Name of data' and saved (id 23) with comment 'Comment about something'
// Done something 'Name of data' and saved (id 23) with limit 2
// Done something 'Name of data' and saved (id 23) with comment 'Comment about something' and limit 2
// Done something 'Name of data' and saved (id 23, sent notification)
// Done something 'Name of data' and saved (id 23, sent notification) with limit 2
// Done something 'Name of data' and saved (id 23, sent notification) with comment 'Comment about something'
// Done something 'Name of data' and saved (id 23, sent notification) with comment 'Comment about something' and limit 2
我可以手动编码:
String notificationMessage = sentNotification ? ", sent notification" : "";
String commentMessage = comment != null ? String.format(" with comment '%s'", comment) : "";
String limitMessage = "";
if (limit != null) {
limitMessage = String.format("limit %s", limit);
limitMessage = comment != null ? String.format(" and %s", limitMessage) : String.format(" with %s", limitMessage);
}
log.info("Done something '{}' and saved (id {}{}){}{}",
something.getName(), id, notificationMessage, commentMessage, limitMessage);
但难写、难读、复杂且容易出错。
我想要指定部分日志。
示例伪代码:
log.info("Done something '{}' and saved (id {} $notification) $parameters",
something.getName(), id,
$notification: sentNotification ? "sent notification" : "",
$parameters: [comment, limit]);
它应该支持可选参数,用给定的字符串替换布尔/条件,支持分隔空格、逗号和单词with和and。
也许有这方面的现有图书馆?或者也许至少有一种更简单的编码方式?
如果没有,我只需要编写自己的库来记录消息。此外,这种库将提供所有日志都是一致的。
如果您没有发现三个可选参数有问题,可以想象还有更多(而且您不能总是将它们打包到一个类中 - 另一个仅用于参数记录的类层会导致更复杂的情况)。
最后,我知道我可以分别记录每个操作。但是有了这个,我会得到更多的日志,而且我不会在一个地方拥有最重要的信息。其他日志在debug 级别,而不是info。
【问题讨论】:
标签: java log4j log4j2 logback slf4j