View Javadoc

    1   /**
    2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
    3    */
    4   package net.sourceforge.pmd.util;
    5
    6   import java.io.PrintWriter;
    7   import java.io.StringWriter;
    8   import java.util.logging.Formatter;
    9   import java.util.logging.Handler;
    10  import java.util.logging.Level;
    11  import java.util.logging.LogRecord;
    12
    13  import org.apache.tools.ant.Project;
    14  import org.apache.tools.ant.Task;
    15
    16  /**
    17   * AntLogHandler sends log messages to an Ant Task, so the regular Ant logging
    18   * is used.
    19   *
    20   * @author Wouter Zelle
    21   */
    22  public class AntLogHandler extends Handler {
    23      private Task antTask;
    24
    25      private static final Formatter FORMATTER = new PmdLogFormatter();
    26
    27      public AntLogHandler(Task antTask) {
    28          this.antTask = antTask;
    29      }
    30
    31      public void publish(LogRecord logRecord) {
    32          //Map the log levels from java.util.logging to Ant
    33          int antLevel;
    34          Level level = logRecord.getLevel();
    35          if (level == Level.FINEST)
    36              antLevel = Project.MSG_DEBUG;   //Shown when -debug is supplied to Ant
    37          else if (level == Level.FINE || level == Level.FINER || level == Level.CONFIG)
    38              antLevel = Project.MSG_VERBOSE; //Shown when -verbose is supplied to Ant
    39          else if (level == Level.INFO)
    40              antLevel = Project.MSG_INFO;    //Always shown
    41          else if (level == Level.WARNING)
    42              antLevel = Project.MSG_WARN;    //Always shown
    43          else if (level == Level.SEVERE)
    44              antLevel = Project.MSG_ERR;     //Always shown
    45          else
    46              throw new IllegalStateException("Unknown logging level");   //shouldn't get ALL or NONE
    47
    48          antTask.log(FORMATTER.format(logRecord), antLevel);
    49          if (logRecord.getThrown() != null) {
    50              StringWriter stringWriter = new StringWriter();
    51              PrintWriter printWriter = new PrintWriter(stringWriter, true);
    52              logRecord.getThrown().printStackTrace(printWriter);
    53              antTask.log(stringWriter.toString(), antLevel);
    54          }
    55      }
    56
    57      public void close() throws SecurityException {
    58          return;
    59      }
    60
    61      public void flush() {
    62          return;
    63      }
    64  }