package io.dropwizard.servlets.tasks;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.google.common.collect.ImmutableMultimap;
import org.slf4j.ILoggerFactory;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.PrintWriter;
import java.util.List;
public class LogConfigurationTask extends Task {
private final ILoggerFactory loggerContext;
public LogConfigurationTask() {
this(LoggerFactory.getILoggerFactory());
}
public LogConfigurationTask(ILoggerFactory loggerContext) {
super("log-level");
this.loggerContext = loggerContext;
}
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception {
final List<String> loggerNames = getLoggerNames(parameters);
final Level loggerLevel = getLoggerLevel(parameters);
for (String loggerName : loggerNames) {
((LoggerContext) loggerContext).getLogger(loggerName).setLevel(loggerLevel);
output.println(String.format("Configured logging level for %s to %s", loggerName, loggerLevel));
output.flush();
}
}
private List<String> getLoggerNames(ImmutableMultimap<String, String> parameters) {
return parameters.get("logger").asList();
}
@Nullable
private Level getLoggerLevel(ImmutableMultimap<String, String> parameters) {
final List<String> loggerLevels = parameters.get("level").asList();
return loggerLevels.isEmpty() ? null : Level.valueOf(loggerLevels.get(0));
}
}