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
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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.length() > 0) {
  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. Stack<TimedElement> threadStack = threadStacks.get(Thread.currentThread());
  181. if (threadStack == null) {
  182. threadStack = new Stack<>();
  183. threadStacks.put(Thread.currentThread(), threadStack);
  184. }
  185. /* For debugging purposes uncomment:
  186. org.w3c.dom.Comment s = doc.createComment("stack=" + threadStack);
  187. buildElement.element.appendChild(s);
  188. */
  189. return threadStack;
  190. }
  191. /**
  192. * Fired when a target starts building, this pushes a timed element
  193. * for the target onto the stack of elements for the current thread,
  194. * remembering the current time and the name of the target.
  195. *
  196. * @param event An event with any relevant extra information.
  197. * Will not be <code>null</code>.
  198. */
  199. @Override
  200. public void targetStarted(BuildEvent event) {
  201. Target target = event.getTarget();
  202. TimedElement targetElement = new TimedElement();
  203. targetElement.startTime = System.currentTimeMillis();
  204. targetElement.element = doc.createElement(TARGET_TAG);
  205. targetElement.element.setAttribute(NAME_ATTR, target.getName());
  206. targets.put(target, targetElement);
  207. getStack().push(targetElement);
  208. }
  209. /**
  210. * Fired when a target finishes building, this adds the time taken
  211. * and any error stacktrace to the appropriate target element in the log.
  212. *
  213. * @param event An event with any relevant extra information.
  214. * Will not be <code>null</code>.
  215. */
  216. @Override
  217. public void targetFinished(BuildEvent event) {
  218. Target target = event.getTarget();
  219. TimedElement targetElement = targets.get(target);
  220. if (targetElement != null) {
  221. long totalTime = System.currentTimeMillis() - targetElement.startTime;
  222. targetElement.element.setAttribute(TIME_ATTR, DefaultLogger.formatTime(totalTime));
  223. TimedElement parentElement = null;
  224. Stack<TimedElement> threadStack = getStack();
  225. if (!threadStack.empty()) {
  226. TimedElement poppedStack = threadStack.pop();
  227. if (poppedStack != targetElement) {
  228. throw new RuntimeException("Mismatch - popped element = " + poppedStack //NOSONAR
  229. + " finished target element = " + targetElement);
  230. }
  231. if (!threadStack.empty()) {
  232. parentElement = threadStack.peek();
  233. }
  234. }
  235. if (parentElement == null) {
  236. synchronizedAppend(buildElement.element, targetElement.element);
  237. } else {
  238. synchronizedAppend(parentElement.element,
  239. targetElement.element);
  240. }
  241. }
  242. targets.remove(target);
  243. }
  244. /**
  245. * Fired when a task starts building, this pushes a timed element
  246. * for the task onto the stack of elements for the current thread,
  247. * remembering the current time and the name of the task.
  248. *
  249. * @param event An event with any relevant extra information.
  250. * Will not be <code>null</code>.
  251. */
  252. @Override
  253. public void taskStarted(BuildEvent event) {
  254. TimedElement taskElement = new TimedElement();
  255. taskElement.startTime = System.currentTimeMillis();
  256. taskElement.element = doc.createElement(TASK_TAG);
  257. Task task = event.getTask();
  258. String name = event.getTask().getTaskName();
  259. if (name == null) {
  260. name = "";
  261. }
  262. taskElement.element.setAttribute(NAME_ATTR, name);
  263. taskElement.element.setAttribute(LOCATION_ATTR, event.getTask().getLocation().toString());
  264. tasks.put(task, taskElement);
  265. getStack().push(taskElement);
  266. }
  267. /**
  268. * Fired when a task finishes building, this adds the time taken
  269. * and any error stacktrace to the appropriate task element in the log.
  270. *
  271. * @param event An event with any relevant extra information.
  272. * Will not be <code>null</code>.
  273. */
  274. @Override
  275. public void taskFinished(BuildEvent event) {
  276. Task task = event.getTask();
  277. TimedElement taskElement = tasks.get(task);
  278. if (taskElement == null) {
  279. throw new RuntimeException("Unknown task " + task + " not in " + tasks); //NOSONAR
  280. }
  281. long totalTime = System.currentTimeMillis() - taskElement.startTime;
  282. taskElement.element.setAttribute(TIME_ATTR, DefaultLogger.formatTime(totalTime));
  283. Target target = task.getOwningTarget();
  284. TimedElement targetElement = null;
  285. if (target != null) {
  286. targetElement = targets.get(target);
  287. }
  288. if (targetElement == null) {
  289. synchronizedAppend(buildElement.element, taskElement.element);
  290. } else {
  291. synchronizedAppend(targetElement.element, taskElement.element);
  292. }
  293. Stack<TimedElement> threadStack = getStack();
  294. if (!threadStack.empty()) {
  295. TimedElement poppedStack = threadStack.pop();
  296. if (poppedStack != taskElement) {
  297. throw new RuntimeException("Mismatch - popped element = " + poppedStack //NOSONAR
  298. + " finished task element = " + taskElement);
  299. }
  300. }
  301. tasks.remove(task);
  302. }
  303. /**
  304. * Get the TimedElement associated with a task.
  305. *
  306. * Where the task is not found directly, search for unknown elements which
  307. * may be hiding the real task
  308. */
  309. private TimedElement getTaskElement(Task task) {
  310. TimedElement element = tasks.get(task);
  311. if (element != null) {
  312. return element;
  313. }
  314. for (Enumeration<Task> e = tasks.keys(); e.hasMoreElements();) {
  315. Task key = e.nextElement();
  316. if (key instanceof UnknownElement
  317. && ((UnknownElement) key).getTask() == task) {
  318. return tasks.get(key);
  319. }
  320. }
  321. return null;
  322. }
  323. /**
  324. * Fired when a message is logged, this adds a message element to the
  325. * most appropriate parent element (task, target or build) and records
  326. * the priority and text of the message.
  327. *
  328. * @param event An event with any relevant extra information.
  329. * Will not be <code>null</code>.
  330. */
  331. @Override
  332. public void messageLogged(BuildEvent event) {
  333. int priority = event.getPriority();
  334. if (priority > msgOutputLevel) {
  335. return;
  336. }
  337. Element messageElement = doc.createElement(MESSAGE_TAG);
  338. String name;
  339. switch (priority) {
  340. case Project.MSG_ERR:
  341. name = "error";
  342. break;
  343. case Project.MSG_WARN:
  344. name = "warn";
  345. break;
  346. case Project.MSG_INFO:
  347. name = "info";
  348. break;
  349. default:
  350. name = "debug";
  351. break;
  352. }
  353. messageElement.setAttribute(PRIORITY_ATTR, name);
  354. Throwable ex = event.getException();
  355. if (Project.MSG_DEBUG <= msgOutputLevel && ex != null) {
  356. Text errText = doc.createCDATASection(StringUtils.getStackTrace(ex));
  357. Element stacktrace = doc.createElement(STACKTRACE_TAG);
  358. stacktrace.appendChild(errText);
  359. synchronizedAppend(buildElement.element, stacktrace);
  360. }
  361. Text messageText = doc.createCDATASection(event.getMessage());
  362. messageElement.appendChild(messageText);
  363. TimedElement parentElement = null;
  364. Task task = event.getTask();
  365. Target target = event.getTarget();
  366. if (task != null) {
  367. parentElement = getTaskElement(task);
  368. }
  369. if (parentElement == null && target != null) {
  370. parentElement = targets.get(target);
  371. }
  372. if (parentElement != null) {
  373. synchronizedAppend(parentElement.element, messageElement);
  374. } else {
  375. synchronizedAppend(buildElement.element, messageElement);
  376. }
  377. }
  378. // -------------------------------------------------- BuildLogger interface
  379. /**
  380. * Set the logging level when using this as a Logger
  381. *
  382. * @param level the logging level -
  383. * see {@link org.apache.tools.ant.Project#MSG_ERR Project}
  384. * class for level definitions
  385. */
  386. @Override
  387. public void setMessageOutputLevel(int level) {
  388. msgOutputLevel = level;
  389. }
  390. /**
  391. * Set the output stream to which logging output is sent when operating
  392. * as a logger.
  393. *
  394. * @param output the output PrintStream.
  395. */
  396. @Override
  397. public void setOutputPrintStream(PrintStream output) {
  398. this.outStream = new PrintStream(output, true);
  399. }
  400. /**
  401. * Ignore emacs mode, as it has no meaning in XML format
  402. *
  403. * @param emacsMode true if logger should produce emacs compatible
  404. * output
  405. */
  406. @Override
  407. public void setEmacsMode(boolean emacsMode) {
  408. }
  409. /**
  410. * Ignore error print stream. All output will be written to
  411. * either the XML log file or the PrintStream provided to
  412. * setOutputPrintStream
  413. *
  414. * @param err the stream we are going to ignore.
  415. */
  416. @Override
  417. public void setErrorPrintStream(PrintStream err) {
  418. }
  419. private void synchronizedAppend(Node parent, Node child) {
  420. synchronized(parent) {
  421. parent.appendChild(child);
  422. }
  423. }
  424. }