1. /*
  2. * Copyright 2000-2004 The Apache Software Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package org.apache.tools.ant;
  18. import java.io.FileOutputStream;
  19. import java.io.IOException;
  20. import java.io.OutputStream;
  21. import java.io.OutputStreamWriter;
  22. import java.io.PrintStream;
  23. import java.io.Writer;
  24. import java.util.Hashtable;
  25. import java.util.Stack;
  26. import java.util.Enumeration;
  27. import javax.xml.parsers.DocumentBuilder;
  28. import javax.xml.parsers.DocumentBuilderFactory;
  29. import org.apache.tools.ant.util.DOMElementWriter;
  30. import org.apache.tools.ant.util.StringUtils;
  31. import org.w3c.dom.Document;
  32. import org.w3c.dom.Element;
  33. import org.w3c.dom.Text;
  34. /**
  35. * Generates a file in the current directory with
  36. * an XML description of what happened during a build.
  37. * The default filename is "log.xml", but this can be overridden
  38. * with the property <code>XmlLogger.file</code>.
  39. *
  40. * This implementation assumes in its sanity checking that only one
  41. * thread runs a particular target/task at a time. This is enforced
  42. * by the way that parallel builds and antcalls are done - and
  43. * indeed all but the simplest of tasks could run into problems
  44. * if executed in parallel.
  45. *
  46. * @see Project#addBuildListener(BuildListener)
  47. */
  48. public class XmlLogger implements BuildLogger {
  49. private int msgOutputLevel = Project.MSG_DEBUG;
  50. private PrintStream outStream;
  51. /** DocumentBuilder to use when creating the document to start with. */
  52. private static DocumentBuilder builder = getDocumentBuilder();
  53. /**
  54. * Returns a default DocumentBuilder instance or throws an
  55. * ExceptionInInitializerError if it can't be created.
  56. *
  57. * @return a default DocumentBuilder instance.
  58. */
  59. private static DocumentBuilder getDocumentBuilder() {
  60. try {
  61. return DocumentBuilderFactory.newInstance().newDocumentBuilder();
  62. } catch (Exception exc) {
  63. throw new ExceptionInInitializerError(exc);
  64. }
  65. }
  66. /** XML element name for a build. */
  67. private static final String BUILD_TAG = "build";
  68. /** XML element name for a target. */
  69. private static final String TARGET_TAG = "target";
  70. /** XML element name for a task. */
  71. private static final String TASK_TAG = "task";
  72. /** XML element name for a message. */
  73. private static final String MESSAGE_TAG = "message";
  74. /** XML attribute name for a name. */
  75. private static final String NAME_ATTR = "name";
  76. /** XML attribute name for a time. */
  77. private static final String TIME_ATTR = "time";
  78. /** XML attribute name for a message priority. */
  79. private static final String PRIORITY_ATTR = "priority";
  80. /** XML attribute name for a file location. */
  81. private static final String LOCATION_ATTR = "location";
  82. /** XML attribute name for an error description. */
  83. private static final String ERROR_ATTR = "error";
  84. /** XML element name for a stack trace. */
  85. private static final String STACKTRACE_TAG = "stacktrace";
  86. /** The complete log document for this build. */
  87. private Document doc = builder.newDocument();
  88. /** Mapping for when tasks started (Task to TimedElement). */
  89. private Hashtable tasks = new Hashtable();
  90. /** Mapping for when targets started (Task to TimedElement). */
  91. private Hashtable targets = new Hashtable();
  92. /**
  93. * Mapping of threads to stacks of elements
  94. * (Thread to Stack of TimedElement).
  95. */
  96. private Hashtable threadStacks = new Hashtable();
  97. /**
  98. * When the build started.
  99. */
  100. private TimedElement buildElement = null;
  101. /** Utility class representing the time an element started. */
  102. private static class TimedElement {
  103. /**
  104. * Start time in milliseconds
  105. * (as returned by <code>System.currentTimeMillis()</code>).
  106. */
  107. private long startTime;
  108. /** Element created at the start time. */
  109. private Element element;
  110. public String toString() {
  111. return element.getTagName() + ":" + element.getAttribute("name");
  112. }
  113. }
  114. /**
  115. * Constructs a new BuildListener that logs build events to an XML file.
  116. */
  117. public XmlLogger() {
  118. }
  119. /**
  120. * Fired when the build starts, this builds the top-level element for the
  121. * document and remembers the time of the start of the build.
  122. *
  123. * @param event Ignored.
  124. */
  125. public void buildStarted(BuildEvent event) {
  126. buildElement = new TimedElement();
  127. buildElement.startTime = System.currentTimeMillis();
  128. buildElement.element = doc.createElement(BUILD_TAG);
  129. }
  130. /**
  131. * Fired when the build finishes, this adds the time taken and any
  132. * error stacktrace to the build element and writes the document to disk.
  133. *
  134. * @param event An event with any relevant extra information.
  135. * Will not be <code>null</code>.
  136. */
  137. public void buildFinished(BuildEvent event) {
  138. long totalTime = System.currentTimeMillis() - buildElement.startTime;
  139. buildElement.element.setAttribute(TIME_ATTR,
  140. DefaultLogger.formatTime(totalTime));
  141. if (event.getException() != null) {
  142. buildElement.element.setAttribute(ERROR_ATTR,
  143. event.getException().toString());
  144. // print the stacktrace in the build file it is always useful...
  145. // better have too much info than not enough.
  146. Throwable t = event.getException();
  147. Text errText = doc.createCDATASection(StringUtils.getStackTrace(t));
  148. Element stacktrace = doc.createElement(STACKTRACE_TAG);
  149. stacktrace.appendChild(errText);
  150. buildElement.element.appendChild(stacktrace);
  151. }
  152. String outFilename = event.getProject().getProperty("XmlLogger.file");
  153. if (outFilename == null) {
  154. outFilename = "log.xml";
  155. }
  156. String xslUri
  157. = event.getProject().getProperty("ant.XmlLogger.stylesheet.uri");
  158. if (xslUri == null) {
  159. xslUri = "log.xsl";
  160. }
  161. Writer out = null;
  162. try {
  163. // specify output in UTF8 otherwise accented characters will blow
  164. // up everything
  165. OutputStream stream = outStream;
  166. if (stream == null) {
  167. stream = new FileOutputStream(outFilename);
  168. }
  169. out = new OutputStreamWriter(stream, "UTF8");
  170. out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  171. if (xslUri.length() > 0) {
  172. out.write("<?xml-stylesheet type=\"text/xsl\" href=\""
  173. + xslUri + "\"?>\n\n");
  174. }
  175. (new DOMElementWriter()).write(buildElement.element, out, 0, "\t");
  176. out.flush();
  177. } catch (IOException exc) {
  178. throw new BuildException("Unable to write log file", exc);
  179. } finally {
  180. if (out != null) {
  181. try {
  182. out.close();
  183. } catch (IOException e) {
  184. // ignore
  185. }
  186. }
  187. }
  188. buildElement = null;
  189. }
  190. /**
  191. * Returns the stack of timed elements for the current thread.
  192. * @return the stack of timed elements for the current thread
  193. */
  194. private Stack getStack() {
  195. Stack threadStack = (Stack) threadStacks.get(Thread.currentThread());
  196. if (threadStack == null) {
  197. threadStack = new Stack();
  198. threadStacks.put(Thread.currentThread(), threadStack);
  199. }
  200. /* For debugging purposes uncomment:
  201. org.w3c.dom.Comment s = doc.createComment("stack=" + threadStack);
  202. buildElement.element.appendChild(s);
  203. */
  204. return threadStack;
  205. }
  206. /**
  207. * Fired when a target starts building, this pushes a timed element
  208. * for the target onto the stack of elements for the current thread,
  209. * remembering the current time and the name of the target.
  210. *
  211. * @param event An event with any relevant extra information.
  212. * Will not be <code>null</code>.
  213. */
  214. public void targetStarted(BuildEvent event) {
  215. Target target = event.getTarget();
  216. TimedElement targetElement = new TimedElement();
  217. targetElement.startTime = System.currentTimeMillis();
  218. targetElement.element = doc.createElement(TARGET_TAG);
  219. targetElement.element.setAttribute(NAME_ATTR, target.getName());
  220. targets.put(target, targetElement);
  221. getStack().push(targetElement);
  222. }
  223. /**
  224. * Fired when a target finishes building, this adds the time taken
  225. * and any error stacktrace to the appropriate target element in the log.
  226. *
  227. * @param event An event with any relevant extra information.
  228. * Will not be <code>null</code>.
  229. */
  230. public void targetFinished(BuildEvent event) {
  231. Target target = event.getTarget();
  232. TimedElement targetElement = (TimedElement) targets.get(target);
  233. if (targetElement != null) {
  234. long totalTime
  235. = System.currentTimeMillis() - targetElement.startTime;
  236. targetElement.element.setAttribute(TIME_ATTR,
  237. DefaultLogger.formatTime(totalTime));
  238. TimedElement parentElement = null;
  239. Stack threadStack = getStack();
  240. if (!threadStack.empty()) {
  241. TimedElement poppedStack = (TimedElement) threadStack.pop();
  242. if (poppedStack != targetElement) {
  243. throw new RuntimeException("Mismatch - popped element = "
  244. + poppedStack
  245. + " finished target element = "
  246. + targetElement);
  247. }
  248. if (!threadStack.empty()) {
  249. parentElement = (TimedElement) threadStack.peek();
  250. }
  251. }
  252. if (parentElement == null) {
  253. buildElement.element.appendChild(targetElement.element);
  254. } else {
  255. parentElement.element.appendChild(targetElement.element);
  256. }
  257. }
  258. targets.remove(target);
  259. }
  260. /**
  261. * Fired when a task starts building, this pushes a timed element
  262. * for the task onto the stack of elements for the current thread,
  263. * remembering the current time and the name of the task.
  264. *
  265. * @param event An event with any relevant extra information.
  266. * Will not be <code>null</code>.
  267. */
  268. public void taskStarted(BuildEvent event) {
  269. TimedElement taskElement = new TimedElement();
  270. taskElement.startTime = System.currentTimeMillis();
  271. taskElement.element = doc.createElement(TASK_TAG);
  272. Task task = event.getTask();
  273. String name = event.getTask().getTaskName();
  274. taskElement.element.setAttribute(NAME_ATTR, name);
  275. taskElement.element.setAttribute(LOCATION_ATTR,
  276. event.getTask().getLocation().toString());
  277. tasks.put(task, taskElement);
  278. getStack().push(taskElement);
  279. }
  280. /**
  281. * Fired when a task finishes building, this adds the time taken
  282. * and any error stacktrace to the appropriate task element in the log.
  283. *
  284. * @param event An event with any relevant extra information.
  285. * Will not be <code>null</code>.
  286. */
  287. public void taskFinished(BuildEvent event) {
  288. Task task = event.getTask();
  289. TimedElement taskElement = (TimedElement) tasks.get(task);
  290. if (taskElement != null) {
  291. long totalTime = System.currentTimeMillis() - taskElement.startTime;
  292. taskElement.element.setAttribute(TIME_ATTR,
  293. DefaultLogger.formatTime(totalTime));
  294. Target target = task.getOwningTarget();
  295. TimedElement targetElement = null;
  296. if (target != null) {
  297. targetElement = (TimedElement) targets.get(target);
  298. }
  299. if (targetElement == null) {
  300. buildElement.element.appendChild(taskElement.element);
  301. } else {
  302. targetElement.element.appendChild(taskElement.element);
  303. }
  304. Stack threadStack = getStack();
  305. if (!threadStack.empty()) {
  306. TimedElement poppedStack = (TimedElement) threadStack.pop();
  307. if (poppedStack != taskElement) {
  308. throw new RuntimeException("Mismatch - popped element = "
  309. + poppedStack + " finished task element = "
  310. + taskElement);
  311. }
  312. }
  313. tasks.remove(task);
  314. } else {
  315. throw new RuntimeException("Unknown task " + task + " not in " + tasks);
  316. }
  317. }
  318. /**
  319. * Get the TimedElement associated with a task.
  320. *
  321. * Where the task is not found directly, search for unknown elements which
  322. * may be hiding the real task
  323. */
  324. private TimedElement getTaskElement(Task task) {
  325. TimedElement element = (TimedElement) tasks.get(task);
  326. if (element != null) {
  327. return element;
  328. }
  329. for (Enumeration e = tasks.keys(); e.hasMoreElements();) {
  330. Task key = (Task) e.nextElement();
  331. if (key instanceof UnknownElement) {
  332. if (((UnknownElement) key).getTask() == task) {
  333. return (TimedElement) tasks.get(key);
  334. }
  335. }
  336. }
  337. return null;
  338. }
  339. /**
  340. * Fired when a message is logged, this adds a message element to the
  341. * most appropriate parent element (task, target or build) and records
  342. * the priority and text of the message.
  343. *
  344. * @param event An event with any relevant extra information.
  345. * Will not be <code>null</code>.
  346. */
  347. public void messageLogged(BuildEvent event) {
  348. int priority = event.getPriority();
  349. if (priority > msgOutputLevel) {
  350. return;
  351. }
  352. Element messageElement = doc.createElement(MESSAGE_TAG);
  353. String name = "debug";
  354. switch (event.getPriority()) {
  355. case Project.MSG_ERR:
  356. name = "error";
  357. break;
  358. case Project.MSG_WARN:
  359. name = "warn";
  360. break;
  361. case Project.MSG_INFO:
  362. name = "info";
  363. break;
  364. default:
  365. name = "debug";
  366. break;
  367. }
  368. messageElement.setAttribute(PRIORITY_ATTR, name);
  369. Text messageText = doc.createCDATASection(event.getMessage());
  370. messageElement.appendChild(messageText);
  371. TimedElement parentElement = null;
  372. Task task = event.getTask();
  373. Target target = event.getTarget();
  374. if (task != null) {
  375. parentElement = getTaskElement(task);
  376. }
  377. if (parentElement == null && target != null) {
  378. parentElement = (TimedElement) targets.get(target);
  379. }
  380. /*
  381. if (parentElement == null) {
  382. Stack threadStack
  383. = (Stack) threadStacks.get(Thread.currentThread());
  384. if (threadStack != null) {
  385. if (!threadStack.empty()) {
  386. parentElement = (TimedElement) threadStack.peek();
  387. }
  388. }
  389. }
  390. */
  391. if (parentElement != null) {
  392. parentElement.element.appendChild(messageElement);
  393. } else {
  394. buildElement.element.appendChild(messageElement);
  395. }
  396. }
  397. // -------------------------------------------------- BuildLogger interface
  398. /**
  399. * Set the logging level when using this as a Logger
  400. *
  401. * @param level the logging level -
  402. * see {@link org.apache.tools.ant.Project#MSG_ERR Project}
  403. * class for level definitions
  404. */
  405. public void setMessageOutputLevel(int level) {
  406. msgOutputLevel = level;
  407. }
  408. /**
  409. * Set the output stream to which logging output is sent when operating
  410. * as a logger.
  411. *
  412. * @param output the output PrintStream.
  413. */
  414. public void setOutputPrintStream(PrintStream output) {
  415. this.outStream = new PrintStream(output, true);
  416. }
  417. /**
  418. * Ignore emacs mode, as it has no meaning in XML format
  419. *
  420. * @param emacsMode true if logger should produce emacs compatible
  421. * output
  422. */
  423. public void setEmacsMode(boolean emacsMode) {
  424. }
  425. /**
  426. * Ignore error print stream. All output will be written to
  427. * either the XML log file or the PrintStream provided to
  428. * setOutputPrintStream
  429. *
  430. * @param err the stream we are going to ignore.
  431. */
  432. public void setErrorPrintStream(PrintStream err) {
  433. }
  434. }