XMLFormatter.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /* XMLFormatter.java --
  2. A class for formatting log messages into a standard XML format
  3. Copyright (C) 2002, 2004 Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.util.logging;
  33. import gnu.java.lang.CPStringBuilder;
  34. import java.text.SimpleDateFormat;
  35. import java.util.Date;
  36. import java.util.ResourceBundle;
  37. /**
  38. * An <code>XMLFormatter</code> formats LogRecords into
  39. * a standard XML format.
  40. *
  41. * @author Sascha Brawer (brawer@acm.org)
  42. */
  43. public class XMLFormatter
  44. extends Formatter
  45. {
  46. /**
  47. * Constructs a new XMLFormatter.
  48. */
  49. public XMLFormatter()
  50. {
  51. }
  52. /**
  53. * The character sequence that is used to separate lines in the
  54. * generated XML stream. Somewhat surprisingly, the Sun J2SE 1.4
  55. * reference implementation always uses UNIX line endings, even on
  56. * platforms that have different line ending conventions (i.e.,
  57. * DOS). The GNU Classpath implementation does not replicates this
  58. * bug.
  59. *
  60. * See also the Sun bug parade, bug #4462871,
  61. * "java.util.logging.SimpleFormatter uses hard-coded line separator".
  62. */
  63. private static final String lineSep = SimpleFormatter.lineSep;
  64. /**
  65. * A DateFormat for emitting time in the ISO 8601 format.
  66. * Since the API specification of SimpleDateFormat does not talk
  67. * about its thread-safety, we cannot share a singleton instance.
  68. */
  69. private final SimpleDateFormat iso8601
  70. = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
  71. /**
  72. * Appends a line consisting of indentation, opening element tag,
  73. * element content, closing element tag and line separator to
  74. * a CPStringBuilder, provided that the element content is
  75. * actually existing.
  76. *
  77. * @param buf the CPStringBuilder to which the line will be appended.
  78. *
  79. * @param indent the indentation level.
  80. *
  81. * @param tag the element tag name, for instance <code>method</code>.
  82. *
  83. * @param content the element content, or <code>null</code> to
  84. * have no output whatsoever appended to <code>buf</code>.
  85. */
  86. private static void appendTag(CPStringBuilder buf, int indent,
  87. String tag, String content)
  88. {
  89. int i;
  90. if (content == null)
  91. return;
  92. for (i = 0; i < indent * 2; i++)
  93. buf.append(' ');
  94. buf.append("<");
  95. buf.append(tag);
  96. buf.append('>');
  97. /* Append the content, but escape for XML by replacing
  98. * '&', '<', '>' and all non-ASCII characters with
  99. * appropriate escape sequences.
  100. * The Sun J2SE 1.4 reference implementation does not
  101. * escape non-ASCII characters. This is a bug in their
  102. * implementation which has been reported in the Java
  103. * bug parade as bug number (FIXME: Insert number here).
  104. */
  105. for (i = 0; i < content.length(); i++)
  106. {
  107. char c = content.charAt(i);
  108. switch (c)
  109. {
  110. case '&':
  111. buf.append("&amp;");
  112. break;
  113. case '<':
  114. buf.append("&lt;");
  115. break;
  116. case '>':
  117. buf.append("&gt;");
  118. break;
  119. default:
  120. if (((c >= 0x20) && (c <= 0x7e))
  121. || (c == /* line feed */ 10)
  122. || (c == /* carriage return */ 13))
  123. buf.append(c);
  124. else
  125. {
  126. buf.append("&#");
  127. buf.append((int) c);
  128. buf.append(';');
  129. }
  130. break;
  131. } /* switch (c) */
  132. } /* for i */
  133. buf.append("</");
  134. buf.append(tag);
  135. buf.append(">");
  136. buf.append(lineSep);
  137. }
  138. /**
  139. * Appends a line consisting of indentation, opening element tag,
  140. * numeric element content, closing element tag and line separator
  141. * to a CPStringBuilder.
  142. *
  143. * @param buf the CPStringBuilder to which the line will be appended.
  144. *
  145. * @param indent the indentation level.
  146. *
  147. * @param tag the element tag name, for instance <code>method</code>.
  148. *
  149. * @param content the element content.
  150. */
  151. private static void appendTag(CPStringBuilder buf, int indent,
  152. String tag, long content)
  153. {
  154. appendTag(buf, indent, tag, Long.toString(content));
  155. }
  156. public String format(LogRecord record)
  157. {
  158. CPStringBuilder buf = new CPStringBuilder(400);
  159. Level level = record.getLevel();
  160. long millis = record.getMillis();
  161. Object[] params = record.getParameters();
  162. ResourceBundle bundle = record.getResourceBundle();
  163. String message;
  164. buf.append("<record>");
  165. buf.append(lineSep);
  166. appendTag(buf, 1, "date", iso8601.format(new Date(millis)));
  167. appendTag(buf, 1, "millis", millis);
  168. appendTag(buf, 1, "sequence", record.getSequenceNumber());
  169. appendTag(buf, 1, "logger", record.getLoggerName());
  170. if (level.isStandardLevel())
  171. appendTag(buf, 1, "level", level.toString());
  172. else
  173. appendTag(buf, 1, "level", level.intValue());
  174. appendTag(buf, 1, "class", record.getSourceClassName());
  175. appendTag(buf, 1, "method", record.getSourceMethodName());
  176. appendTag(buf, 1, "thread", record.getThreadID());
  177. /* The Sun J2SE 1.4 reference implementation does not emit the
  178. * message in localized form. This is in violation of the API
  179. * specification. The GNU Classpath implementation intentionally
  180. * replicates the buggy behavior of the Sun implementation, as
  181. * different log files might be a big nuisance to users.
  182. */
  183. try
  184. {
  185. record.setResourceBundle(null);
  186. message = formatMessage(record);
  187. }
  188. finally
  189. {
  190. record.setResourceBundle(bundle);
  191. }
  192. appendTag(buf, 1, "message", message);
  193. /* The Sun J2SE 1.4 reference implementation does not
  194. * emit key, catalog and param tags. This is in violation
  195. * of the API specification. The Classpath implementation
  196. * intentionally replicates the buggy behavior of the
  197. * Sun implementation, as different log files might be
  198. * a big nuisance to users.
  199. *
  200. * FIXME: File a bug report with Sun. Insert bug number here.
  201. *
  202. *
  203. * key = record.getMessage();
  204. * if (key == null)
  205. * key = "";
  206. *
  207. * if ((bundle != null) && !key.equals(message))
  208. * {
  209. * appendTag(buf, 1, "key", key);
  210. * appendTag(buf, 1, "catalog", record.getResourceBundleName());
  211. * }
  212. *
  213. * if (params != null)
  214. * {
  215. * for (int i = 0; i < params.length; i++)
  216. * appendTag(buf, 1, "param", params[i].toString());
  217. * }
  218. */
  219. /* FIXME: We have no way to obtain the stacktrace before free JVMs
  220. * support the corresponding method in java.lang.Throwable. Well,
  221. * it would be possible to parse the output of printStackTrace,
  222. * but this would be pretty kludgy. Instead, we postpose the
  223. * implementation until Throwable has made progress.
  224. */
  225. Throwable thrown = record.getThrown();
  226. if (thrown != null)
  227. {
  228. buf.append(" <exception>");
  229. buf.append(lineSep);
  230. /* The API specification is not clear about what exactly
  231. * goes into the XML record for a thrown exception: It
  232. * could be the result of getMessage(), getLocalizedMessage(),
  233. * or toString(). Therefore, it was necessary to write a
  234. * Mauve testlet and run it with the Sun J2SE 1.4 reference
  235. * implementation. It turned out that the we need to call
  236. * toString().
  237. *
  238. * FIXME: File a bug report with Sun, asking for clearer
  239. * specs.
  240. */
  241. appendTag(buf, 2, "message", thrown.toString());
  242. /* FIXME: The Logging DTD specifies:
  243. *
  244. * <!ELEMENT exception (message?, frame+)>
  245. *
  246. * However, java.lang.Throwable.getStackTrace() is
  247. * allowed to return an empty array. So, what frame should
  248. * be emitted for an empty stack trace? We probably
  249. * should file a bug report with Sun, asking for the DTD
  250. * to be changed.
  251. */
  252. buf.append(" </exception>");
  253. buf.append(lineSep);
  254. }
  255. buf.append("</record>");
  256. buf.append(lineSep);
  257. return buf.toString();
  258. }
  259. /**
  260. * Returns a string that handlers are supposed to emit before
  261. * the first log record. The base implementation returns an
  262. * empty string, but subclasses such as {@link XMLFormatter}
  263. * override this method in order to provide a suitable header.
  264. *
  265. * @return a string for the header.
  266. *
  267. * @param h the handler which will prepend the returned
  268. * string in front of the first log record. This method
  269. * will inspect certain properties of the handler, for
  270. * example its encoding, in order to construct the header.
  271. */
  272. public String getHead(Handler h)
  273. {
  274. CPStringBuilder buf;
  275. String encoding;
  276. buf = new CPStringBuilder(80);
  277. buf.append("<?xml version=\"1.0\" encoding=\"");
  278. encoding = h.getEncoding();
  279. /* file.encoding is a system property with the Sun JVM, indicating
  280. * the platform-default file encoding. Unfortunately, the API
  281. * specification for java.lang.System.getProperties() does not
  282. * list this property.
  283. */
  284. if (encoding == null)
  285. encoding = System.getProperty("file.encoding");
  286. /* Since file.encoding is not listed with the API specification of
  287. * java.lang.System.getProperties(), there might be some VMs that
  288. * do not define this system property. Therefore, we use UTF-8 as
  289. * a reasonable default. Please note that if the platform encoding
  290. * uses the same codepoints as US-ASCII for the US-ASCII character
  291. * set (e.g, 65 for A), it does not matter whether we emit the
  292. * wrong encoding into the XML header -- the GNU Classpath will
  293. * emit XML escape sequences like &#1234; for any non-ASCII
  294. * character. Virtually all character encodings use the same code
  295. * points as US-ASCII for ASCII characters. Probably, EBCDIC is
  296. * the only exception.
  297. */
  298. if (encoding == null)
  299. encoding = "UTF-8";
  300. /* On Windows XP localized for Swiss German (this is one of
  301. * my [Sascha Brawer's] test machines), the default encoding
  302. * has the canonical name "windows-1252". The "historical" name
  303. * of this encoding is "Cp1252" (see the Javadoc for the class
  304. * java.nio.charset.Charset for the distinction). Now, that class
  305. * does have a method for mapping historical to canonical encoding
  306. * names. However, if we used it here, we would be come dependent
  307. * on java.nio.*, which was only introduced with J2SE 1.4.
  308. * Thus, we do this little hack here. As soon as Classpath supports
  309. * java.nio.charset.CharSet, this hack should be replaced by
  310. * code that correctly canonicalizes the encoding name.
  311. */
  312. if ((encoding.length() > 2) && encoding.startsWith("Cp"))
  313. encoding = "windows-" + encoding.substring(2);
  314. buf.append(encoding);
  315. buf.append("\" standalone=\"no\"?>");
  316. buf.append(lineSep);
  317. /* SYSTEM is not a fully qualified URL so that validating
  318. * XML parsers do not need to connect to the Internet in
  319. * order to read in a log file. See also the Sun Bug Parade,
  320. * bug #4372790, "Logging APIs: need to use relative URL for XML
  321. * doctype".
  322. */
  323. buf.append("<!DOCTYPE log SYSTEM \"logger.dtd\">");
  324. buf.append(lineSep);
  325. buf.append("<log>");
  326. buf.append(lineSep);
  327. return buf.toString();
  328. }
  329. public String getTail(Handler h)
  330. {
  331. return "</log>" + lineSep;
  332. }
  333. }