[core] Hack to get Ant's log level

- Very ugly, uses reflection and is limited to the few
implementatations that come with Ant itself or and testutils
 - Intended as a starting point for fixing #1018
This commit is contained in:
Juan Martín Sotuyo Dodero
2018-05-07 01:46:40 -03:00
parent 21ee3f76ed
commit cf914f424d
2 changed files with 46 additions and 4 deletions

View File

@@ -12,8 +12,6 @@ import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Handler;
import java.util.logging.Level;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
@@ -271,8 +269,8 @@ public class PMDTaskImpl {
}
public void execute() throws BuildException {
final Handler antLogHandler = new AntLogHandler(project);
final ScopedLogHandlersManager logManager = new ScopedLogHandlersManager(Level.FINEST, antLogHandler);
final AntLogHandler antLogHandler = new AntLogHandler(project);
final ScopedLogHandlersManager logManager = new ScopedLogHandlersManager(antLogHandler.getAntLogLevel(), antLogHandler);
try {
doTask();
} finally {

View File

@@ -6,11 +6,13 @@ package net.sourceforge.pmd.util.log;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.apache.tools.ant.BuildListener;
import org.apache.tools.ant.Project;
/**
@@ -23,10 +25,52 @@ public class AntLogHandler extends Handler {
private Project project;
private static final Formatter FORMATTER = new PmdLogFormatter();
private static final Level[] LOG_LEVELS = new Level[] {
Level.SEVERE, Level.WARNING, Level.INFO, Level.CONFIG, Level.FINEST,
};
public AntLogHandler(Project project) {
this.project = project;
}
public Level getAntLogLevel() {
Class<?> clazz;
int maxLevel = Project.MSG_ERR;
for (final BuildListener l : project.getBuildListeners()) {
clazz = l.getClass();
Field declaredField = null;
try {
while (BuildListener.class.isAssignableFrom(clazz)) {
try {
declaredField = l.getClass().getDeclaredField("msgOutputLevel");
} catch (final NoSuchFieldException ignored) {
try {
declaredField = l.getClass().getDeclaredField("logLevel");
} catch (final NoSuchFieldException expected) {
// ignore it
}
}
if (declaredField != null) {
break;
}
clazz = clazz.getSuperclass();
}
if (declaredField != null) {
declaredField.setAccessible(true);
final int level = declaredField.getInt(l);
if (maxLevel < level) {
maxLevel = level;
}
}
} catch (final IllegalArgumentException | IllegalAccessException ignored) {
// Just ignore it
}
}
return LOG_LEVELS[maxLevel];
}
@Override
public void publish(LogRecord logRecord) {