FileHandler.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. /* FileHandler.java -- a class for publishing log messages to log files
  2. Copyright (C) 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.util.logging;
  32. import gnu.java.lang.CPStringBuilder;
  33. import java.io.File;
  34. import java.io.FileOutputStream;
  35. import java.io.FilterOutputStream;
  36. import java.io.IOException;
  37. import java.io.OutputStream;
  38. import java.util.LinkedList;
  39. import java.util.ListIterator;
  40. /**
  41. * A <code>FileHandler</code> publishes log records to a set of log
  42. * files. A maximum file size can be specified; as soon as a log file
  43. * reaches the size limit, it is closed and the next file in the set
  44. * is taken.
  45. *
  46. * <p><strong>Configuration:</strong> Values of the subsequent
  47. * <code>LogManager</code> properties are taken into consideration
  48. * when a <code>FileHandler</code> is initialized. If a property is
  49. * not defined, or if it has an invalid value, a default is taken
  50. * without an exception being thrown.
  51. *
  52. * <ul>
  53. *
  54. * <li><code>java.util.FileHandler.level</code> - specifies
  55. * the initial severity level threshold. Default value:
  56. * <code>Level.ALL</code>.</li>
  57. *
  58. * <li><code>java.util.FileHandler.filter</code> - specifies
  59. * the name of a Filter class. Default value: No Filter.</li>
  60. *
  61. * <li><code>java.util.FileHandler.formatter</code> - specifies
  62. * the name of a Formatter class. Default value:
  63. * <code>java.util.logging.XMLFormatter</code>.</li>
  64. *
  65. * <li><code>java.util.FileHandler.encoding</code> - specifies
  66. * the name of the character encoding. Default value:
  67. * the default platform encoding.</li>
  68. *
  69. * <li><code>java.util.FileHandler.limit</code> - specifies the number
  70. * of bytes a log file is approximately allowed to reach before it
  71. * is closed and the handler switches to the next file in the
  72. * rotating set. A value of zero means that files can grow
  73. * without limit. Default value: 0 (unlimited growth).</li>
  74. *
  75. * <li><code>java.util.FileHandler.count</code> - specifies the number
  76. * of log files through which this handler cycles. Default value:
  77. * 1.</li>
  78. *
  79. * <li><code>java.util.FileHandler.pattern</code> - specifies a
  80. * pattern for the location and name of the produced log files.
  81. * See the section on <a href="#filePatterns">file name
  82. * patterns</a> for details. Default value:
  83. * <code>"%h/java%u.log"</code>.</li>
  84. *
  85. * <li><code>java.util.FileHandler.append</code> - specifies
  86. * whether the handler will append log records to existing
  87. * files, or whether the handler will clear log files
  88. * upon switching to them. Default value: <code>false</code>,
  89. * indicating that files will be cleared.</li>
  90. *
  91. * </ul>
  92. *
  93. * <p><a name="filePatterns"><strong>File Name Patterns:</strong></a>
  94. * The name and location and log files are specified with pattern
  95. * strings. The handler will replace the following character sequences
  96. * when opening log files:
  97. *
  98. * <p><ul>
  99. * <li><code>/</code> - replaced by the platform-specific path name
  100. * separator. This value is taken from the system property
  101. * <code>file.separator</code>.</li>
  102. *
  103. * <li><code>%t</code> - replaced by the platform-specific location of
  104. * the directory intended for temporary files. This value is
  105. * taken from the system property <code>java.io.tmpdir</code>.</li>
  106. *
  107. * <li><code>%h</code> - replaced by the location of the home
  108. * directory of the current user. This value is taken from the
  109. * system property <code>user.home</code>.</li>
  110. *
  111. * <li><code>%g</code> - replaced by a generation number for
  112. * distinguisthing the individual items in the rotating set
  113. * of log files. The generation number cycles through the
  114. * sequence 0, 1, ..., <code>count</code> - 1.</li>
  115. *
  116. * <li><code>%u</code> - replaced by a unique number for
  117. * distinguisthing the output files of several concurrently
  118. * running processes. The <code>FileHandler</code> starts
  119. * with 0 when it tries to open a log file. If the file
  120. * cannot be opened because it is currently in use,
  121. * the unique number is incremented by one and opening
  122. * is tried again. These steps are repeated until the
  123. * opening operation succeeds.
  124. *
  125. * <p>FIXME: Is the following correct? Please review. The unique
  126. * number is determined for each log file individually when it is
  127. * opened upon switching to the next file. Therefore, it is not
  128. * correct to assume that all log files in a rotating set bear the
  129. * same unique number.
  130. *
  131. * <p>FIXME: The Javadoc for the Sun reference implementation
  132. * says: "Note that the use of unique ids to avoid conflicts is
  133. * only guaranteed to work reliably when using a local disk file
  134. * system." Why? This needs to be mentioned as well, in case
  135. * the reviewers decide the statement is true. Otherwise,
  136. * file a bug report with Sun.</li>
  137. *
  138. * <li><code>%%</code> - replaced by a single percent sign.</li>
  139. * </ul>
  140. *
  141. * <p>If the pattern string does not contain <code>%g</code> and
  142. * <code>count</code> is greater than one, the handler will append
  143. * the string <code>.%g</code> to the specified pattern.
  144. *
  145. * <p>If the handler attempts to open a log file, this log file
  146. * is being used at the time of the attempt, and the pattern string
  147. * does not contain <code>%u</code>, the handler will append
  148. * the string <code>.%u</code> to the specified pattern. This
  149. * step is performed after any generation number has been
  150. * appended.
  151. *
  152. * <p><em>Examples for the GNU platform:</em>
  153. *
  154. * <p><ul>
  155. *
  156. * <li><code>%h/java%u.log</code> will lead to a single log file
  157. * <code>/home/janet/java0.log</code>, assuming <code>count</code>
  158. * equals 1, the user's home directory is
  159. * <code>/home/janet</code>, and the attempt to open the file
  160. * succeeds.</li>
  161. *
  162. * <li><code>%h/java%u.log</code> will lead to three log files
  163. * <code>/home/janet/java0.log.0</code>,
  164. * <code>/home/janet/java0.log.1</code>, and
  165. * <code>/home/janet/java0.log.2</code>,
  166. * assuming <code>count</code> equals 3, the user's home
  167. * directory is <code>/home/janet</code>, and all attempts
  168. * to open files succeed.</li>
  169. *
  170. * <li><code>%h/java%u.log</code> will lead to three log files
  171. * <code>/home/janet/java0.log.0</code>,
  172. * <code>/home/janet/java1.log.1</code>, and
  173. * <code>/home/janet/java0.log.2</code>,
  174. * assuming <code>count</code> equals 3, the user's home
  175. * directory is <code>/home/janet</code>, and the attempt
  176. * to open <code>/home/janet/java0.log.1</code> fails.</li>
  177. *
  178. * </ul>
  179. *
  180. * @author Sascha Brawer (brawer@acm.org)
  181. */
  182. public class FileHandler
  183. extends StreamHandler
  184. {
  185. /**
  186. * A literal that prefixes all file-handler related properties in the
  187. * logging.properties file.
  188. */
  189. private static final String PROPERTY_PREFIX = "java.util.logging.FileHandler";
  190. /**
  191. * The name of the property to set for specifying a file naming (incl. path)
  192. * pattern to use with rotating log files.
  193. */
  194. private static final String PATTERN_KEY = PROPERTY_PREFIX + ".pattern";
  195. /**
  196. * The default pattern to use when the <code>PATTERN_KEY</code> property was
  197. * not specified in the logging.properties file.
  198. */
  199. private static final String DEFAULT_PATTERN = "%h/java%u.log";
  200. /**
  201. * The name of the property to set for specifying an approximate maximum
  202. * amount, in bytes, to write to any one log output file. A value of zero
  203. * (which is the default) implies a no limit.
  204. */
  205. private static final String LIMIT_KEY = PROPERTY_PREFIX + ".limit";
  206. private static final int DEFAULT_LIMIT = 0;
  207. /**
  208. * The name of the property to set for specifying how many output files to
  209. * cycle through. The default value is 1.
  210. */
  211. private static final String COUNT_KEY = PROPERTY_PREFIX + ".count";
  212. private static final int DEFAULT_COUNT = 1;
  213. /**
  214. * The name of the property to set for specifying whether this handler should
  215. * append, or not, its output to existing files. The default value is
  216. * <code>false</code> meaning NOT to append.
  217. */
  218. private static final String APPEND_KEY = PROPERTY_PREFIX + ".append";
  219. private static final boolean DEFAULT_APPEND = false;
  220. /**
  221. * The number of bytes a log file is approximately allowed to reach
  222. * before it is closed and the handler switches to the next file in
  223. * the rotating set. A value of zero means that files can grow
  224. * without limit.
  225. */
  226. private final int limit;
  227. /**
  228. * The number of log files through which this handler cycles.
  229. */
  230. private final int count;
  231. /**
  232. * The pattern for the location and name of the produced log files.
  233. * See the section on <a href="#filePatterns">file name patterns</a>
  234. * for details.
  235. */
  236. private final String pattern;
  237. /**
  238. * Indicates whether the handler will append log records to existing
  239. * files (<code>true</code>), or whether the handler will clear log files
  240. * upon switching to them (<code>false</code>).
  241. */
  242. private final boolean append;
  243. /**
  244. * The number of bytes that have currently been written to the stream.
  245. * Package private for use in inner classes.
  246. */
  247. long written;
  248. /**
  249. * A linked list of files we are, or have written to. The entries
  250. * are file path strings, kept in the order
  251. */
  252. private LinkedList logFiles;
  253. /**
  254. * Constructs a <code>FileHandler</code>, taking all property values
  255. * from the current {@link LogManager LogManager} configuration.
  256. *
  257. * @throws java.io.IOException FIXME: The Sun Javadoc says: "if
  258. * there are IO problems opening the files." This conflicts
  259. * with the general principle that configuration errors do
  260. * not prohibit construction. Needs review.
  261. *
  262. * @throws SecurityException if a security manager exists and
  263. * the caller is not granted the permission to control
  264. * the logging infrastructure.
  265. */
  266. public FileHandler()
  267. throws IOException, SecurityException
  268. {
  269. this(LogManager.getLogManager().getProperty(PATTERN_KEY),
  270. LogManager.getIntProperty(LIMIT_KEY, DEFAULT_LIMIT),
  271. LogManager.getIntProperty(COUNT_KEY, DEFAULT_COUNT),
  272. LogManager.getBooleanProperty(APPEND_KEY, DEFAULT_APPEND));
  273. }
  274. /* FIXME: Javadoc missing. */
  275. public FileHandler(String pattern)
  276. throws IOException, SecurityException
  277. {
  278. this(pattern, DEFAULT_LIMIT, DEFAULT_COUNT, DEFAULT_APPEND);
  279. }
  280. /* FIXME: Javadoc missing. */
  281. public FileHandler(String pattern, boolean append)
  282. throws IOException, SecurityException
  283. {
  284. this(pattern, DEFAULT_LIMIT, DEFAULT_COUNT, append);
  285. }
  286. /* FIXME: Javadoc missing. */
  287. public FileHandler(String pattern, int limit, int count)
  288. throws IOException, SecurityException
  289. {
  290. this(pattern, limit, count,
  291. LogManager.getBooleanProperty(APPEND_KEY, DEFAULT_APPEND));
  292. }
  293. /**
  294. * Constructs a <code>FileHandler</code> given the pattern for the
  295. * location and name of the produced log files, the size limit, the
  296. * number of log files thorough which the handler will rotate, and
  297. * the <code>append</code> property. All other property values are
  298. * taken from the current {@link LogManager LogManager}
  299. * configuration.
  300. *
  301. * @param pattern The pattern for the location and name of the
  302. * produced log files. See the section on <a
  303. * href="#filePatterns">file name patterns</a> for details.
  304. * If <code>pattern</code> is <code>null</code>, the value is
  305. * taken from the {@link LogManager LogManager} configuration
  306. * property
  307. * <code>java.util.logging.FileHandler.pattern</code>.
  308. * However, this is a pecularity of the GNU implementation,
  309. * and Sun's API specification does not mention what behavior
  310. * is to be expected for <code>null</code>. Therefore,
  311. * applications should not rely on this feature.
  312. *
  313. * @param limit specifies the number of bytes a log file is
  314. * approximately allowed to reach before it is closed and the
  315. * handler switches to the next file in the rotating set. A
  316. * value of zero means that files can grow without limit.
  317. *
  318. * @param count specifies the number of log files through which this
  319. * handler cycles.
  320. *
  321. * @param append specifies whether the handler will append log
  322. * records to existing files (<code>true</code>), or whether the
  323. * handler will clear log files upon switching to them
  324. * (<code>false</code>).
  325. *
  326. * @throws java.io.IOException FIXME: The Sun Javadoc says: "if
  327. * there are IO problems opening the files." This conflicts
  328. * with the general principle that configuration errors do
  329. * not prohibit construction. Needs review.
  330. *
  331. * @throws SecurityException if a security manager exists and
  332. * the caller is not granted the permission to control
  333. * the logging infrastructure.
  334. * <p>FIXME: This seems in contrast to all other handler
  335. * constructors -- verify this by running tests against
  336. * the Sun reference implementation.
  337. */
  338. public FileHandler(String pattern,
  339. int limit,
  340. int count,
  341. boolean append)
  342. throws IOException, SecurityException
  343. {
  344. super(/* output stream, created below */ null,
  345. PROPERTY_PREFIX,
  346. /* default level */ Level.ALL,
  347. /* formatter */ null,
  348. /* default formatter */ XMLFormatter.class);
  349. if ((limit <0) || (count < 1))
  350. throw new IllegalArgumentException();
  351. this.pattern = pattern != null ? pattern : DEFAULT_PATTERN;
  352. this.limit = limit;
  353. this.count = count;
  354. this.append = append;
  355. this.written = 0;
  356. this.logFiles = new LinkedList ();
  357. setOutputStream (createFileStream (this.pattern, limit, count, append,
  358. /* generation */ 0));
  359. }
  360. /* FIXME: Javadoc missing. */
  361. private OutputStream createFileStream(String pattern,
  362. int limit,
  363. int count,
  364. boolean append,
  365. int generation)
  366. {
  367. String path;
  368. int unique = 0;
  369. /* Throws a SecurityException if the caller does not have
  370. * LoggingPermission("control").
  371. */
  372. LogManager.getLogManager().checkAccess();
  373. /* Default value from the java.util.logging.FileHandler.pattern
  374. * LogManager configuration property.
  375. */
  376. if (pattern == null)
  377. pattern = LogManager.getLogManager().getProperty(PATTERN_KEY);
  378. if (pattern == null)
  379. pattern = DEFAULT_PATTERN;
  380. if (count > 1 && !has (pattern, 'g'))
  381. pattern = pattern + ".%g";
  382. do
  383. {
  384. path = replaceFileNameEscapes(pattern, generation, unique, count);
  385. try
  386. {
  387. File file = new File(path);
  388. if (!file.exists () || append)
  389. {
  390. FileOutputStream fout = new FileOutputStream (file, append);
  391. // FIXME we need file locks for this to work properly, but they
  392. // are not implemented yet in Classpath! Madness!
  393. // FileChannel channel = fout.getChannel ();
  394. // FileLock lock = channel.tryLock ();
  395. // if (lock != null) // We've locked the file.
  396. // {
  397. if (logFiles.isEmpty ())
  398. logFiles.addFirst (path);
  399. return new ostr (fout);
  400. // }
  401. }
  402. }
  403. catch (Exception ex)
  404. {
  405. reportError (null, ex, ErrorManager.OPEN_FAILURE);
  406. }
  407. unique = unique + 1;
  408. if (!has (pattern, 'u'))
  409. pattern = pattern + ".%u";
  410. }
  411. while (true);
  412. }
  413. /**
  414. * Replaces the substrings <code>"/"</code> by the value of the
  415. * system property <code>"file.separator"</code>, <code>"%t"</code>
  416. * by the value of the system property
  417. * <code>"java.io.tmpdir"</code>, <code>"%h"</code> by the value of
  418. * the system property <code>"user.home"</code>, <code>"%g"</code>
  419. * by the value of <code>generation</code>, <code>"%u"</code> by the
  420. * value of <code>uniqueNumber</code>, and <code>"%%"</code> by a
  421. * single percent character. If <code>pattern</code> does
  422. * <em>not</em> contain the sequence <code>"%g"</code>,
  423. * the value of <code>generation</code> will be appended to
  424. * the result.
  425. *
  426. * @throws NullPointerException if one of the system properties
  427. * <code>"file.separator"</code>,
  428. * <code>"java.io.tmpdir"</code>, or
  429. * <code>"user.home"</code> has no value and the
  430. * corresponding escape sequence appears in
  431. * <code>pattern</code>.
  432. */
  433. private static String replaceFileNameEscapes(String pattern,
  434. int generation,
  435. int uniqueNumber,
  436. int count)
  437. {
  438. CPStringBuilder buf = new CPStringBuilder(pattern);
  439. String replaceWith;
  440. boolean foundGeneration = false;
  441. int pos = 0;
  442. do
  443. {
  444. // Uncomment the next line for finding bugs.
  445. // System.out.println(buf.substring(0,pos) + '|' + buf.substring(pos));
  446. if (buf.charAt(pos) == '/')
  447. {
  448. /* The same value is also provided by java.io.File.separator. */
  449. replaceWith = System.getProperty("file.separator");
  450. buf.replace(pos, pos + 1, replaceWith);
  451. pos = pos + replaceWith.length() - 1;
  452. continue;
  453. }
  454. if (buf.charAt(pos) == '%')
  455. {
  456. switch (buf.charAt(pos + 1))
  457. {
  458. case 't':
  459. replaceWith = System.getProperty("java.io.tmpdir");
  460. break;
  461. case 'h':
  462. replaceWith = System.getProperty("user.home");
  463. break;
  464. case 'g':
  465. replaceWith = Integer.toString(generation);
  466. foundGeneration = true;
  467. break;
  468. case 'u':
  469. replaceWith = Integer.toString(uniqueNumber);
  470. break;
  471. case '%':
  472. replaceWith = "%";
  473. break;
  474. default:
  475. replaceWith = "??";
  476. break; // FIXME: Throw exception?
  477. }
  478. buf.replace(pos, pos + 2, replaceWith);
  479. pos = pos + replaceWith.length() - 1;
  480. continue;
  481. }
  482. }
  483. while (++pos < buf.length() - 1);
  484. if (!foundGeneration && (count > 1))
  485. {
  486. buf.append('.');
  487. buf.append(generation);
  488. }
  489. return buf.toString();
  490. }
  491. /* FIXME: Javadoc missing. */
  492. public void publish(LogRecord record)
  493. {
  494. if (limit > 0 && written >= limit)
  495. rotate ();
  496. super.publish(record);
  497. flush ();
  498. }
  499. /**
  500. * Rotates the current log files, possibly removing one if we
  501. * exceed the file count.
  502. */
  503. private synchronized void rotate ()
  504. {
  505. if (logFiles.size () > 0)
  506. {
  507. File f1 = null;
  508. ListIterator lit = null;
  509. // If we reach the file count, ditch the oldest file.
  510. if (logFiles.size () == count)
  511. {
  512. f1 = new File ((String) logFiles.getLast ());
  513. f1.delete ();
  514. lit = logFiles.listIterator (logFiles.size () - 1);
  515. }
  516. // Otherwise, move the oldest to a new location.
  517. else
  518. {
  519. String path = replaceFileNameEscapes (pattern, logFiles.size (),
  520. /* unique */ 0, count);
  521. f1 = new File (path);
  522. logFiles.addLast (path);
  523. lit = logFiles.listIterator (logFiles.size () - 1);
  524. }
  525. // Now rotate the files.
  526. while (lit.hasPrevious ())
  527. {
  528. String s = (String) lit.previous ();
  529. File f2 = new File (s);
  530. f2.renameTo (f1);
  531. f1 = f2;
  532. }
  533. }
  534. setOutputStream (createFileStream (pattern, limit, count, append,
  535. /* generation */ 0));
  536. // Reset written count.
  537. written = 0;
  538. }
  539. /**
  540. * Tell if <code>pattern</code> contains the pattern sequence
  541. * with character <code>escape</code>. That is, if <code>escape</code>
  542. * is 'g', this method returns true if the given pattern contains
  543. * "%g", and not just the substring "%g" (for example, in the case of
  544. * "%%g").
  545. *
  546. * @param pattern The pattern to test.
  547. * @param escape The escape character to search for.
  548. * @return True iff the pattern contains the escape sequence with the
  549. * given character.
  550. */
  551. private static boolean has (final String pattern, final char escape)
  552. {
  553. final int len = pattern.length ();
  554. boolean sawPercent = false;
  555. for (int i = 0; i < len; i++)
  556. {
  557. char c = pattern.charAt (i);
  558. if (sawPercent)
  559. {
  560. if (c == escape)
  561. return true;
  562. if (c == '%') // Double percent
  563. {
  564. sawPercent = false;
  565. continue;
  566. }
  567. }
  568. sawPercent = (c == '%');
  569. }
  570. return false;
  571. }
  572. /**
  573. * An output stream that tracks the number of bytes written to it.
  574. */
  575. private final class ostr extends FilterOutputStream
  576. {
  577. private ostr (OutputStream out)
  578. {
  579. super (out);
  580. }
  581. public void write (final int b) throws IOException
  582. {
  583. out.write (b);
  584. FileHandler.this.written++; // FIXME: synchronize?
  585. }
  586. public void write (final byte[] b) throws IOException
  587. {
  588. write (b, 0, b.length);
  589. }
  590. public void write (final byte[] b, final int offset, final int length)
  591. throws IOException
  592. {
  593. out.write (b, offset, length);
  594. FileHandler.this.written += length; // FIXME: synchronize?
  595. }
  596. }
  597. }