SLF4J使用Java21字符串模板的实现


JDK 21 通过 JEP430 引入了字符串模板。这个是SLF4J使用字符串模板的处理器案例,点击标题

这是使用 JDK 21 中的新字符串模板功能与日志记录框架(在本例中为 SLF4J)一起使用的概念证明。

在类 LOG 中,将处理器创建为每个日志级别的静态字段。这些可以静态导入并调用,如下所示:

import static de.darenkster.stringtemplates2slf4j.loggers.LOG.*;
...
var test = "log";
var ex = new Exception();
INFO.
"This is a info \{test}";
ERROR.
"This is a error \{test} \{ex}";
WARN.
"This is a debug \{test}";
TRACE.
"This is a debug \{test}";

日志输出:

10:33:44.899 [main] INFO de.darenkster.stringtemplates2slf4j.Main -- This is a info log
10:33:44.907 [main] ERROR de.darenkster.stringtemplates2slf4j.Main -- This is a error log java.lang.Exception
java.lang.Exception: null
  at de.darenkster.stringtemplates2slf4j.Main.main(Main.java:9)
10:33:44.909 [main] DEBUG de.darenkster.stringtemplates2slf4j.Main -- This is a debug log
10:33:44.910 [main] WARN de.darenkster.stringtemplates2slf4j.Main -- This is a warn log

不同的记录器(信息、调试、错误等)在LOG类中定义为字段并静态初始化。
调用类通过 StackWalker API 确定,并根据字符串模板是否包含异常,调用带有可抛出参数的相应日志方法。