tags:

views:

546

answers:

1

I have initialized a java.util.logging.Logger bean and now want to add a Handler which I've also created a bean for. The trouble is the Logger method is called addHandler instead of something like setHandler.

How can I inject the handler into the logger?

Do I need to wrap Logger in a Spring-friendly bean class?

EDIT

If someone can also tell me how to pass in the logging level (which is a static value) I'd be much obliged.

+4  A: 

UPDATE: Changed to use java.util.logging, and show how to set level.

You can use this by having a FactoryBean implementation:

package foo.bar;

import java.util.List;
import java.util.logging.Handler;
import java.util.logging.Logger;

import org.springframework.beans.factory.FactoryBean;

public class LoggerFactoryBean implements FactoryBean {

    private final Logger logger;

    public LoggerFactoryBean(java.util.logging.Logger logger,
            List<Handler> handlers) {
        this.logger = logger;
        for (Handler handler : handlers) {
            logger.addHandler(handler);
        }
    }

    @Override
    public Object getObject() throws Exception {
        return logger;
    }

    @Override
    public Class getObjectType() {
        return Logger.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

Then define your bean in XML like:

  <!-- returns logger with handlers -->
  <bean id="logger" class="foo.bar.LoggerFactoryBean">
    <constructor-arg>
      <!-- raw logger without handlers -->
      <bean class="java.util.logging.Logger" factory-method="getAnonymousLogger">
        <property name="level">
          <value>SEVERE</value>
        </property>
      </bean>
    </constructor-arg>
    <constructor-arg>
      <util:list>
        <bean class="java.util.logging.FileHandler" />
      </util:list>
    </constructor-arg>
  </bean>

Example unit test:

package foo.bar;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@ContextConfiguration(locations = { "classpath:/foo/bar/test-config.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class HandlerTest {

    @Autowired
    private Logger logger;

    @Test
    public void testLogger() {
        assertNotNull(logger);
        assertEquals(Level.SEVERE, logger.getLevel());
    }
}
toolkit