You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

XmlLogger.java 17 kB

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