We use Spring to obtain all of our JDBC connections as well as part of our persistence framework. However in order to write our own custom DB appender (it has to be a custom since we are not allowed to use the default DBAppender due to table name standards). How can I obtain reference to spring beans/use autowire at this point from inside the Custom Appender? I would prefer staying within spring instead of using plain JDBC.
Custom 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) {
}
}
Here's how I solved the problem - I get a DataSource
inside the appender's start
method via JNDI and then create my JDBCTemplate. It's worked great for me - no troubles at all.
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
}
}
I don't know if you'll encounter the same problem but I had to use multi-step configuration (as described here) because I was getting SLF4J's "substitue logger" error message (described here).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With