使用SLF4J简化惰性日志记录

3

我在一个Spring Boot应用程序中使用SLF4J和Logback。我有兴趣使用延迟日志记录,经过一些研究,我想出了这个解决方案。

这个解决方案按预期工作,并且在未匹配日志级别时不会调用方法。

logger.debug("Begin proceed aspect Method {} : initiator={} | recepient={} | tx_type={}",
                new Object() {@Override public String toString() { return proceedingJoinPoint.getSignature().getName(); }},
                new Object() {@Override public String toString() { return request.getAgentAlias(); }},
                new Object() {@Override public String toString() { return request.getSubscriberMobile(); }},
                new Object() {@Override public String toString() { return request.getTxType(); }});

可以看出,我一遍又一遍地创建新对象并覆盖toString方法。我不想这样做。有更好的方法吗?

我正在使用Spring Boot starter捆绑的SLF4J 1.7.28版本。请注意,我更喜欢使用SLF4J而不是其他日志框架。

我尝试了slf4j-api 2.0.0-alpha1版本和slf4j-simple绑定,因为它具有logger.atDebug.log()实现。但我无法使其正常工作。

谢谢。

4个回答

1
使用SLF4J V2,这也可以通过流畅的API来实现,例如:log.debug("一些昂贵的评估: {}", () -> doSomethingExpensive())
如果您开发一个Spring Boot应用程序并依赖于Spring进行依赖管理,这意味着需要Spring Boot 3.0或更高版本,因为2.x版本捆绑了SLF4J V1.x。

1
如果您想添加一些条件语句,可以添加一个if语句来检查日志级别是否已启用,然后记录消息。
懒加载被保留,但你将得到类似这样的东西:
if(log.isDebugEnabled()) {
 log.debug(....);
}

1
更好的方法是这样做:

if (logger.isDebugEnabled()) {
    logger.debug("Begin proceed aspect Method {} : initiator={} | recepient={} | tx_type={}",
                 proceedingJoinPoint.getSignature().getName(),
                 request.getAgentAlias(),
                 request.getSubscriberMobile(),
                 request.getTxType());
}

或者:

if (logger.isDebugEnabled()) {
    logger.debug("Begin proceed aspect Method " + proceedingJoinPoint.getSignature().getName() +
                 " : initiator=" + request.getAgentAlias() +
                 " | recepient=" + request.getSubscriberMobile() +
                 " | tx_type=" + request.getTxType());
}

0
根据Simas Jonelius的回答的思路,如果我们不希望改变任何依赖关系,我们可以通过为每个参数定义供应商来进行延迟评估。
Supplier<String> initiator = ()-> proceedingJoinPoint.getSignature().getName();
Supplier<String> recepient = ()-> request.getAgentAlias();
Supplier<String> subscriberMobile = ()-> request.getSubscriberMobile();
Supplier<String> tx_type = ()-> request.getTxType(); ;

logger.debug("Begin proceed aspect Method {} : initiator={} | recepient={} | tx_type={}",
                initiator.get(),
                recepient.get(),
                subscriberMobile.get(),
                tx_type.get());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接