【发布时间】:2019-10-15 16:56:23
【问题描述】:
我正在使用 JAVA-11 开发 spring-boot (2.1.9.RELEASE) 应用程序,并使用 log4j2,版本为 2.12.1。我正在使用自定义 log4j2 附加程序,它实际上将日志保存在数据库中。我尝试使用以下 sn-p 但它不起作用。
public class TestApplication {
static {
System.setProperty("org.springframework.boot.logging.LoggingSystem", "none");
}
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Bean
public ApplicationContextProvider applicationContextProvider() {
return new ApplicationContextProvider();
}
}
而log4j2.xml是
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" monitorInterval="30" packages="test.package">
<Appenders>
<Console name="ConsoleAppender" target="system_out" packages="test.package">
<PatternLayout
pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p %t %x [%X{process-param}] %c - %m%n" />
</Console>
<AccessLog name="accessLogAppender" />
<Async name="asyncAccessLogAppender">
<AppenderRef ref="accessLogAppender" />
</Async>
<Loggers>
<Logger name="AccessFileLogger" level="debug" additivity="false">
<AppenderRef ref="ConsoleAppender" />
<AppenderRef ref="asyncAccessLogAppender" />
</Logger>
<Root level="off" />
</Loggers>
</Configuration>
而自定义日志附加器是
package test.package
@Plugin(name = "AccessLog", category = "Core", elementType = "appender", printObject = true)
public final class AccessLogAppender extends AbstractAppender
{
private static final long serialVersionUID = 1L;
private final ReadWriteLock rwLock = new ReentrantReadWriteLock ();
private final Lock readLock = rwLock.readLock ();
private Connection connection = null;
protected AccessLogAppender (final String name)
{
super (name, null, null);
try
{
connection = // code snippet to get the DB Connection
}
catch (SQLException e)
{
}
}
@PluginFactory
public static AccessLogAppender createAppender (
@PluginAttribute("name") String name)
{
return new AccessLogAppender (name);
}
@Override
public void append (LogEvent event)
{
readLock.lock ();
PreparedStatement ps = null;
try
{
// code snippet to save the log into the DB
}
catch (SQLException e)
{
}
finally
{
readLock.unlock ();
}
}
@Override
public void stop ()
{
if (connection != null)
{
try
{
connection.close ();
}
catch (SQLException e)
{
System.out.println (e.getMessage ());
}
}
}
}
并低于错误。
Caused by: org.apache.logging.log4j.core.config.ConfigurationException: No appenders are available for AsyncAppender asyncAccessLogAppender
【问题讨论】:
-
那么它应该如何在启动时记录东西?
-
当应用程序上下文提供程序可用时,从那时起我只需要日志。
-
我的意思是,这很好,但 Spring 在此之前已经在记录,这就是为什么在其他任何事情之前初始化记录的原因。
-
是的,但我需要在提到的 springboot 文档之一中避免它。
-
这是一个记录器而不是一个附加器。
标签: java spring-boot log4j2