log4j-to-slf4j 没有实现 org.apache.logging.log4j.LogManager

log4j-to-slf4j does not implement org.apache.logging.log4j.LogManager

在我的项目中我使用了slf4j,

该项目包括一个使用 org.apache.logging.log4j:log4j-api:2.14.0

的库

因此,库通过 org.apache.logging.log4j.LogManager.getLogger(abc.class)

获取其记录器

我在我的项目中包含 log4j-to-slf4j-2.x。但是,查看 log4j-to-slf4j-2.x 的内容显示 class.

没有实现

自然地,我的项目在运行时死掉了 NoClassDefFound org/apache/logging/log4j/LogManager

我错过了什么?

这不是 的重复,因为我有一个特定问题需要与链接问题中提出的解决方案不同的解决方案。这个问题需要单独讨论。看不懂就废话收尾!

您将必须使用 LoggerFactory 接口来获取记录器

private static Logger logger = LoggerFactory.getLogger(SLF4JExample.class);

这种方式在任何情况下都适用于 log4jslf4j

log4j-to-slf4j 库适用于您(或库)使用 Log4J 调用 logger.error() 等的情况,但实际上有一个 SLF4J 实现,例如实际处理日志记录的 Logback (例如,您已经在 logback.xml 中配置了 appenders 等)。

您需要继续使用 Log4J 库,LogManager class 存在于此,但 log4j-to-slf4j 成为一个附加层,它将日志记录路由到 SLF4J 及其实现(例如 Logback)。

一些注意事项和注意事项:

Use of this adapter may cause some loss of performance as the Log4j 2 Messages must be formatted before they can be passed to SLF4J. With Log4j 2 as the implementation these would normally be formatted only when they are accessed by a Filter or Appender.

因此,您会在以下情况下使用 log4j-to-slf4j,例如使用 Log4J 的代码(例如库)需要集成到使用 SLF4J 进行日志记录的更大的代码库中,或者一个代码库使用“原始”的类似情况" logging(直接访问LogManager),另一个使用SLF4J,不能轻易修改代码。

Use of the SLF4J adapter (log4j-to-slf4j-2.x.jar) together with the SLF4J bridge (log4j-slf4j-impl-2.x.jar) should never be attempted as it will cause events to endlessly be routed between SLF4J and Log4j 2.

因此,由于 Log4J 是一个 SLF4J 实现,因此可以创建一种情况,程序将使用 Log4J 进行记录,桥接至 SLF4J,SLF4J 将桥接至 SLF4J 实现 (Log4J)...这将再次桥接至SLF4J 等等,无穷无尽。