Skip to content

Instantly share code, notes, and snippets.

@hogelog
Created August 11, 2012 11:28
Show Gist options
  • Save hogelog/3323939 to your computer and use it in GitHub Desktop.
Save hogelog/3323939 to your computer and use it in GitHub Desktop.
Logbackで設定ファイルを切り替える ref: http://qiita.com/items/a62783b0e31a66d33303
package org.hogel;
import java.io.FileNotFoundException;
import java.net.URL;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
public class LoggerConfigLoader {
public static enum Mode {
CONSOLE("logback-console"),
FILE("logback-file");
private final String[] resourceNames;
private Mode(String resourceName) {
resourceNames = new String[] {
'/' + resourceName + "-test.xml",
'/' + resourceName + ".xml",
};
}
public URL getXmlResource() throws FileNotFoundException {
for (String resourceName : resourceNames) {
URL resource = LoggerConfigLoader.class.getResource(resourceName);
if (resource != null) {
return resource;
}
}
throw new FileNotFoundException("resource not found!");
}
}
public static void setMode(Mode mode) throws FileNotFoundException, JoranException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
context.reset();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(context);
URL configUrl = mode.getXmlResource();
configurator.doConfigure(configUrl);
}
}
package org.hogel;
import java.io.FileNotFoundException;
import org.hogel.LoggerConfigLoader.Mode;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.core.joran.spi.JoranException;
public class LoggerConfigLoaderTest {
private static final Logger LOG = LoggerFactory.getLogger("test");
@Test
public void console() throws FileNotFoundException, JoranException {
LoggerConfigLoader.setMode(Mode.CONSOLE);
LOG.debug("console debug!"); // -> stdout
}
@Test
public void file() throws FileNotFoundException, JoranException {
LoggerConfigLoader.setMode(Mode.FILE);
LOG.debug("file debug!"); // -> target/file.log
}
@Test
public void mixed() throws FileNotFoundException, JoranException {
LoggerConfigLoader.setMode(Mode.CONSOLE);
LOG.debug("console debug!"); // -> stdout
LoggerConfigLoader.setMode(Mode.FILE);
LOG.debug("file debug!"); // -> target/file.log
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment