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