KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > ant > DefaultLogger


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */

18
19 package org.apache.tools.ant;
20
21 import java.io.BufferedReader JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.PrintStream JavaDoc;
24 import java.io.StringReader JavaDoc;
25
26 import org.apache.tools.ant.util.DateUtils;
27 import org.apache.tools.ant.util.StringUtils;
28
29 /**
30  * Writes build events to a PrintStream. Currently, it
31  * only writes which targets are being executed, and
32  * any messages that get logged.
33  *
34  */

35 public class DefaultLogger implements BuildLogger {
36     /**
37      * Size of left-hand column for right-justified task name.
38      * @see #messageLogged(BuildEvent)
39      */

40     public static final int LEFT_COLUMN_SIZE = 12;
41
42     // CheckStyle:VisibilityModifier OFF - bc
43
/** PrintStream to write non-error messages to */
44     protected PrintStream JavaDoc out;
45
46     /** PrintStream to write error messages to */
47     protected PrintStream JavaDoc err;
48
49     /** Lowest level of message to write out */
50     protected int msgOutputLevel = Project.MSG_ERR;
51
52     /** Time of the start of the build */
53     private long startTime = System.currentTimeMillis();
54
55     // CheckStyle:ConstantNameCheck OFF - bc
56
/** Line separator */
57     protected static final String JavaDoc lSep = StringUtils.LINE_SEP;
58     // CheckStyle:ConstantNameCheck ON
59

60     /** Whether or not to use emacs-style output */
61     protected boolean emacsMode = false;
62     // CheckStyle:VisibilityModifier ON
63

64
65     /**
66      * Sole constructor.
67      */

68     public DefaultLogger() {
69     }
70
71     /**
72      * Sets the highest level of message this logger should respond to.
73      *
74      * Only messages with a message level lower than or equal to the
75      * given level should be written to the log.
76      * <p>
77      * Constants for the message levels are in the
78      * {@link Project Project} class. The order of the levels, from least
79      * to most verbose, is <code>MSG_ERR</code>, <code>MSG_WARN</code>,
80      * <code>MSG_INFO</code>, <code>MSG_VERBOSE</code>,
81      * <code>MSG_DEBUG</code>.
82      * <p>
83      * The default message level for DefaultLogger is Project.MSG_ERR.
84      *
85      * @param level the logging level for the logger.
86      */

87     public void setMessageOutputLevel(int level) {
88         this.msgOutputLevel = level;
89     }
90
91     /**
92      * Sets the output stream to which this logger is to send its output.
93      *
94      * @param output The output stream for the logger.
95      * Must not be <code>null</code>.
96      */

97     public void setOutputPrintStream(PrintStream JavaDoc output) {
98         this.out = new PrintStream JavaDoc(output, true);
99     }
100
101     /**
102      * Sets the output stream to which this logger is to send error messages.
103      *
104      * @param err The error stream for the logger.
105      * Must not be <code>null</code>.
106      */

107     public void setErrorPrintStream(PrintStream JavaDoc err) {
108         this.err = new PrintStream JavaDoc(err, true);
109     }
110
111     /**
112      * Sets this logger to produce emacs (and other editor) friendly output.
113      *
114      * @param emacsMode <code>true</code> if output is to be unadorned so that
115      * emacs and other editors can parse files names, etc.
116      */

117     public void setEmacsMode(boolean emacsMode) {
118         this.emacsMode = emacsMode;
119     }
120
121     /**
122      * Responds to a build being started by just remembering the current time.
123      *
124      * @param event Ignored.
125      */

126     public void buildStarted(BuildEvent event) {
127         startTime = System.currentTimeMillis();
128     }
129
130     /**
131      * Prints whether the build succeeded or failed,
132      * any errors the occurred during the build, and
133      * how long the build took.
134      *
135      * @param event An event with any relevant extra information.
136      * Must not be <code>null</code>.
137      */

138     public void buildFinished(BuildEvent event) {
139         Throwable JavaDoc error = event.getException();
140         StringBuffer JavaDoc message = new StringBuffer JavaDoc();
141         if (error == null) {
142             message.append(StringUtils.LINE_SEP);
143             message.append(getBuildSuccessfulMessage());
144         } else {
145             message.append(StringUtils.LINE_SEP);
146             message.append(getBuildFailedMessage());
147             message.append(StringUtils.LINE_SEP);
148
149             if (Project.MSG_VERBOSE <= msgOutputLevel
150                 || !(error instanceof BuildException)) {
151                 message.append(StringUtils.getStackTrace(error));
152             } else {
153                 message.append(error.toString()).append(lSep);
154             }
155         }
156         message.append(StringUtils.LINE_SEP);
157         message.append("Total time: ");
158         message.append(formatTime(System.currentTimeMillis() - startTime));
159
160         String JavaDoc msg = message.toString();
161         if (error == null) {
162             printMessage(msg, out, Project.MSG_VERBOSE);
163         } else {
164             printMessage(msg, err, Project.MSG_ERR);
165         }
166         log(msg);
167     }
168
169     /**
170      * This is an override point: the message that indicates whether a build failed.
171      * Subclasses can change/enhance the message.
172      * @return The classic "BUILD FAILED"
173      */

174     protected String JavaDoc getBuildFailedMessage() {
175         return "BUILD FAILED";
176     }
177
178     /**
179      * This is an override point: the message that indicates that a build succeeded.
180      * Subclasses can change/enhance the message.
181      * @return The classic "BUILD SUCCESSFUL"
182      */

183     protected String JavaDoc getBuildSuccessfulMessage() {
184         return "BUILD SUCCESSFUL";
185     }
186
187     /**
188      * Logs a message to say that the target has started if this
189      * logger allows information-level messages.
190      *
191      * @param event An event with any relevant extra information.
192      * Must not be <code>null</code>.
193       */

194     public void targetStarted(BuildEvent event) {
195         if (Project.MSG_INFO <= msgOutputLevel
196             && !event.getTarget().getName().equals("")) {
197             String JavaDoc msg = StringUtils.LINE_SEP
198                 + event.getTarget().getName() + ":";
199             printMessage(msg, out, event.getPriority());
200             log(msg);
201         }
202     }
203
204     /**
205      * No-op implementation.
206      *
207      * @param event Ignored.
208      */

209     public void targetFinished(BuildEvent event) {
210     }
211
212     /**
213      * No-op implementation.
214      *
215      * @param event Ignored.
216      */

217     public void taskStarted(BuildEvent event) {
218     }
219
220     /**
221      * No-op implementation.
222      *
223      * @param event Ignored.
224      */

225     public void taskFinished(BuildEvent event) {
226     }
227
228     /**
229      * Logs a message, if the priority is suitable.
230      * In non-emacs mode, task level messages are prefixed by the
231      * task name which is right-justified.
232      *
233      * @param event A BuildEvent containing message information.
234      * Must not be <code>null</code>.
235      */

236     public void messageLogged(BuildEvent event) {
237         int priority = event.getPriority();
238         // Filter out messages based on priority
239
if (priority <= msgOutputLevel) {
240
241             StringBuffer JavaDoc message = new StringBuffer JavaDoc();
242             if (event.getTask() != null && !emacsMode) {
243                 // Print out the name of the task if we're in one
244
String JavaDoc name = event.getTask().getTaskName();
245                 String JavaDoc label = "[" + name + "] ";
246                 int size = LEFT_COLUMN_SIZE - label.length();
247                 StringBuffer JavaDoc tmp = new StringBuffer JavaDoc();
248                 for (int i = 0; i < size; i++) {
249                     tmp.append(" ");
250                 }
251                 tmp.append(label);
252                 label = tmp.toString();
253
254                 try {
255                     BufferedReader JavaDoc r =
256                         new BufferedReader JavaDoc(
257                             new StringReader JavaDoc(event.getMessage()));
258                     String JavaDoc line = r.readLine();
259                     boolean first = true;
260                     do {
261                         if (first) {
262                             if (line == null) {
263                                 message.append(label);
264                                 break;
265                             }
266                         } else {
267                             message.append(StringUtils.LINE_SEP);
268                         }
269                         first = false;
270                         message.append(label).append(line);
271                         line = r.readLine();
272                     } while (line != null);
273                 } catch (IOException JavaDoc e) {
274                     // shouldn't be possible
275
message.append(label).append(event.getMessage());
276                 }
277             } else {
278                 message.append(event.getMessage());
279             }
280             Throwable JavaDoc ex = event.getException();
281             if (Project.MSG_DEBUG <= msgOutputLevel && ex != null) {
282                     message.append(StringUtils.getStackTrace(ex));
283             }
284
285             String JavaDoc msg = message.toString();
286             if (priority != Project.MSG_ERR) {
287                 printMessage(msg, out, priority);
288             } else {
289                 printMessage(msg, err, priority);
290             }
291             log(msg);
292         }
293     }
294
295     /**
296      * Convenience method to format a specified length of time.
297      *
298      * @param millis Length of time to format, in milliseconds.
299      *
300      * @return the time as a formatted string.
301      *
302      * @see DateUtils#formatElapsedTime(long)
303      */

304     protected static String JavaDoc formatTime(final long millis) {
305         return DateUtils.formatElapsedTime(millis);
306     }
307
308     /**
309      * Prints a message to a PrintStream.
310      *
311      * @param message The message to print.
312      * Should not be <code>null</code>.
313      * @param stream A PrintStream to print the message to.
314      * Must not be <code>null</code>.
315      * @param priority The priority of the message.
316      * (Ignored in this implementation.)
317      */

318     protected void printMessage(final String JavaDoc message,
319                                 final PrintStream JavaDoc stream,
320                                 final int priority) {
321         stream.println(message);
322     }
323
324     /**
325      * Empty implementation which allows subclasses to receive the
326      * same output that is generated here.
327      *
328      * @param message Message being logged. Should not be <code>null</code>.
329      */

330     protected void log(String JavaDoc message) {
331     }
332 }
333
Popular Tags