View Javadoc

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