Search code examples
javaspringspring-bootlogginglogback

Logback Custom Data Base appender for spring boot application


I am creating a java spring boot application and I have a requirement to log (info logs) into specific database table. For this I have created a custom appender class extending AppenderBase class. now the issue is that in my custom appender class I want to create/access a jdbctemplate object using database properties provided in the spring's application.properties file.

How can i access spring's jdbctemplate object in my custom appender?

Here is the code sample -

public class MyDBAppender extends AppenderBase<ILoggingEvent> {

    private JdbcTemplate jdbcTemplate;

    @Override
     protected void append(ILoggingEvent eventObject) {
       jdbcTemplate.savelog(....);
   } 
}

Solution

  • You could make a Spring Bean of your MyDBAppender by adding the @Component annotation on the class level.

    Or if you don't want to do that or if this does not work you can create a helper class to access the ApplicationContext:

    @Component
    public class ApplicationContextProvider implements ApplicationContextAware {
    
        private static ApplicationContext context;
    
        public static <T> T getBean(Class<T> beanType) {
            return context.getBean(beanType);
        }
    
        @Override
        public void setApplicationContext(ApplicationContext ac) throws BeansException {
            context = ac;
        }
    
    }
    

    To access the JdbcTemplate use is it like this.

    JdbcTemplate jdbcTemplate = ApplicationContextProvider.getBean(JdbcTemplate.class);