如何查看是否配置了log4j2
How to check if log4j2 has been configured or not
当您不为 log4j2 提供配置时,我们都熟悉此消息:
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
如何检查 log4j2 是否尚未配置,以便在需要时使用默认配置进行初始化?
在您的应用首次调用 log4j2 代码时,log4j 将在方法 returns 之前配置自身。如果没有找到配置文件,log4j 将使用默认配置自动配置,该配置仅将错误记录到控制台。因此,从您的应用程序的角度来看,永远不会有未配置 log4j 的时候。
一个想法是检查 log4j2.xml 文件是否在类路径中(使用 Class.getResource),如果不在则调用 System.setProperty("log4j.configurationFile", pathToYourConfig)
。请注意,此 必须 在第一次调用 log4j2 API.
之前完成
备选方案:
一旦你有了一个 LoggerContext,你就可以调用
context.setConfigLocation(configLocation)
其中 configLocation 是一个 URI。
这将强制重新配置。
我最终创建了自己的 ConfigurationFactory 并将其注册到
-Dlog4j.configurationFactory
这样您的 ConfigurationFactory 就会知道它是否已被调用。
当您不为 log4j2 提供配置时,我们都熟悉此消息:
ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
如何检查 log4j2 是否尚未配置,以便在需要时使用默认配置进行初始化?
在您的应用首次调用 log4j2 代码时,log4j 将在方法 returns 之前配置自身。如果没有找到配置文件,log4j 将使用默认配置自动配置,该配置仅将错误记录到控制台。因此,从您的应用程序的角度来看,永远不会有未配置 log4j 的时候。
一个想法是检查 log4j2.xml 文件是否在类路径中(使用 Class.getResource),如果不在则调用 System.setProperty("log4j.configurationFile", pathToYourConfig)
。请注意,此 必须 在第一次调用 log4j2 API.
备选方案:
一旦你有了一个 LoggerContext,你就可以调用
context.setConfigLocation(configLocation)
其中 configLocation 是一个 URI。
这将强制重新配置。
我最终创建了自己的 ConfigurationFactory 并将其注册到
-Dlog4j.configurationFactory
这样您的 ConfigurationFactory 就会知道它是否已被调用。