繁体   English   中英

从自定义logback appender使用Spring?

[英]Using Spring from a custom logback appender?

我们使用Spring来获取所有JDBC连接以及持久性框架的一部分。 但是,为了编写我们自己的自定义数据库appender(它必须是自定义的,因为由于表名标准,我们不允许使用默认的DBAppender)。 如何从Custom Appender内部获取spring bean的参考/使用autowire? 我宁愿呆在春天而不是使用普通的JDBC。

自定义Appender:

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;

public class CustomDBAppender extends AppenderBase<ILoggingEvent> {

    protected void append(ILoggingEvent event) {

    }

}

这就是我解决问题的方法 - 我通过JNDI在appender的start方法中获得了一个DataSource ,然后创建了我的JDBCTemplate。 它对我很有用 - 没有任何麻烦。

public class MyAppender extends AppenderBase<ILoggingEvent>
{
  private String _jndiLocation;
  private JDBCTemplate _jt;

  public void setJndiLocation(String jndiLocation)
  {
    _jndiLocation = jndiLocation;
  }

  @Override
  public void start()
  {
    super.start();

    if (_jndiLocation == null)
    {
      throw new IllegalStateException("Must have the JNDI location");
    }
    DataSource ds;
    Context ctx;
    try
    {
      ctx = new InitialContext();
      Object obj = ctx.lookup(_jndiLocation);
      ds= (DataSource) obj;

      if (ds == null)
      {
        throw new IllegalStateException("Failed to obtain data source");
      }
      _jt = new JDBCTemplate(ds);
    }
    catch (Exception ex)
    {
      throw new IllegalStateException("Unable to obtain data source", ex);
    }

  }

  @Override
  protected void append(ILoggingEvent e)
  {
    // log to database here using my JDBCTemplate instance
  }
}

我不知道你是否会遇到同样的问题,但我不得不使用多步配置(如此处所述 ),因为我收到了SLF4J的“substitue logger”错误消息( 此处描述 )。

您的选项在这里受到限制,但您可以使用SingletonBeanFactoryLocator (参见Spring手册, Glue代码和邪恶的单例 )和SpringSource博客条目

我这样做的方法是使用AutowiredAnnotationBeanPostProcessor。

在你的appender的构造函数中,你要求AutowiredAnnotationBeanPostProcessor注入“this”。

我在结束评论这篇文章详细介绍了技术。 本文讨论了一种类似的自动装配Hibernate实体的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM