1. /*
  2. * @(#)FileHandler.java 1.26 03/01/23
  3. *
  4. * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util.logging;
  8. import java.io.*;
  9. import java.nio.channels.FileChannel;
  10. import java.nio.channels.FileLock;
  11. import java.security.*;
  12. /**
  13. * Simple file logging <tt>Handler</tt>.
  14. * <p>
  15. * The <tt>FileHandler</tt> can either write to a specified file,
  16. * or it can write to a rotating set of files.
  17. * <p>
  18. * For a rotating set of files, as each file reaches a given size
  19. * limit, it is closed, rotated out, and a new file opened.
  20. * Successively older files are named by adding "0", "1", "2",
  21. * etc into the base filename.
  22. * <p>
  23. * By default buffering is enabled in the IO libraries but each log
  24. * record is flushed out when it is complete.
  25. * <p>
  26. * By default the <tt>XMLFormatter</tt> class is used for formatting.
  27. * <p>
  28. * <b>Configuration:</b>
  29. * By default each <tt>FileHandler</tt> is initialized using the following
  30. * <tt>LogManager</tt> configuration properties. If properties are not defined
  31. * (or have invalid values) then the specified default values are used.
  32. * <ul>
  33. * <li> java.util.logging.FileHandler.level
  34. * specifies the default level for the <tt>Handler</tt>
  35. * (defaults to <tt>Level.ALL</tt>).
  36. * <li> java.util.logging.FileHandler.filter
  37. * specifies the name of a <tt>Filter</tt> class to use
  38. * (defaults to no <tt>Filter</tt>).
  39. * <li> java.util.logging.FileHandler.formatter
  40. * specifies the name of a </tt>Formatter</tt> class to use
  41. * (defaults to <tt>java.util.logging.XMLFormatter</tt>)
  42. * <li> java.util.logging.FileHandler.encoding
  43. * the name of the character set encoding to use (defaults to
  44. * the default platform encoding).
  45. * <li> java.util.logging.FileHandler.limit
  46. * specifies an approximate maximum amount to write (in bytes)
  47. * to any one file. If this is zero, then there is no limit.
  48. * (Defaults to no limit).
  49. * <li> java.util.logging.FileHandler.count
  50. * specifies how many output files to cycle through (defaults to 1).
  51. * <li> java.util.logging.FileHandler.pattern
  52. * specifies a pattern for generating the output file name. See
  53. * below for details. (Defaults to "%h/java%u.log").
  54. * <li> java.util.logging.FileHandler.append
  55. * specifies whether the FileHandler should append onto
  56. * any existing files (defaults to false).
  57. * </ul>
  58. * <p>
  59. * <p>
  60. * A pattern consists of a string that includes the following special
  61. * components that will be replaced at runtime:
  62. * <ul>
  63. * <li> "/" the local pathname separator
  64. * <li> "%t" the system temporary directory
  65. * <li> "%h" the value of the "user.home" system property
  66. * <li> "%g" the generation number to distinguish rotated logs
  67. * <li> "%u" a unique number to resolve conflicts
  68. * <li> "%%" translates to a single percent sign "%"
  69. * </ul>
  70. * If no "%g" field has been specified and the file count is greater
  71. * than one, then the generation number will be added to the end of
  72. * the generated filename, after a dot.
  73. * <p>
  74. * Thus for example a pattern of "%t/java%g.log" with a count of 2
  75. * would typically cause log files to be written on Solaris to
  76. * /var/tmp/java0.log and /var/tmp/java1.log whereas on Windows 95 they
  77. * would be typically written to to C:\TEMP\java0.log and C:\TEMP\java1.log
  78. * <p>
  79. * Generation numbers follow the sequence 0, 1, 2, etc.
  80. * <p>
  81. * Normally the "%u" unique field is set to 0. However, if the <tt>FileHandler</tt>
  82. * tries to open the filename and finds the file is currently in use by
  83. * another process it will increment the unique number field and try
  84. * again. This will be repeated until <tt>FileHandler</tt> finds a file name that
  85. * is not currently in use. If there is a conflict and no "%u" field has
  86. * been specified, it will be added at the end of the filename after a dot.
  87. * (This will be after any automatically added generation number.)
  88. * <p>
  89. * Thus if three processes were all trying to log to fred%u.%g.txt then
  90. * they might end up using fred0.0.txt, fred1.0.txt, fred2.0.txt as
  91. * the first file in their rotating sequences.
  92. * <p>
  93. * Note that the use of unique ids to avoid conflicts is only guaranteed
  94. * to work reliably when using a local disk file system.
  95. *
  96. * @version 1.26, 01/23/03
  97. * @since 1.4
  98. */
  99. public class FileHandler extends StreamHandler {
  100. private MeteredStream meter;
  101. private boolean append;
  102. private int limit; // zero => no limit.
  103. private int count;
  104. private String pattern;
  105. private String lockFileName;
  106. private FileOutputStream lockStream;
  107. private File files[];
  108. private static final int MAX_LOCKS = 100;
  109. private static java.util.HashMap locks = new java.util.HashMap();
  110. // A metered stream is a subclass of OutputStream that
  111. // (a) forwards all its output to a target stream
  112. // (b) keeps track of how many bytes have been written
  113. private class MeteredStream extends OutputStream {
  114. OutputStream out;
  115. int written;
  116. MeteredStream(OutputStream out, int written) {
  117. this.out = out;
  118. this.written = written;
  119. }
  120. public void write(int b) throws IOException {
  121. out.write(b);
  122. written++;
  123. }
  124. public void write(byte buff[]) throws IOException {
  125. out.write(buff);
  126. written += buff.length;
  127. }
  128. public void write(byte buff[], int off, int len) throws IOException {
  129. out.write(buff,off,len);
  130. written += len;
  131. }
  132. public void flush() throws IOException {
  133. out.flush();
  134. }
  135. public void close() throws IOException {
  136. out.close();
  137. }
  138. }
  139. private void open(File fname, boolean append) throws IOException {
  140. int len = 0;
  141. if (append) {
  142. len = (int)fname.length();
  143. }
  144. FileOutputStream fout = new FileOutputStream(fname.toString(), append);
  145. BufferedOutputStream bout = new BufferedOutputStream(fout);
  146. meter = new MeteredStream(bout, len);
  147. setOutputStream(meter);
  148. }
  149. // Private method to configure a FileHandler from LogManager
  150. // properties and/or default values as specified in the class
  151. // javadoc.
  152. private void configure() {
  153. LogManager manager = LogManager.getLogManager();
  154. String cname = FileHandler.class.getName();
  155. pattern = manager.getStringProperty(cname + ".pattern", "%h/java%u.log");
  156. limit = manager.getIntProperty(cname + ".limit", 0);
  157. if (limit < 0) {
  158. limit = 0;
  159. }
  160. count = manager.getIntProperty(cname + ".count", 1);
  161. if (count <= 0) {
  162. count = 1;
  163. }
  164. append = manager.getBooleanProperty(cname + ".append", false);
  165. setLevel(manager.getLevelProperty(cname + ".level", Level.ALL));
  166. setFilter(manager.getFilterProperty(cname + ".filter", null));
  167. setFormatter(manager.getFormatterProperty(cname + ".formatter", new XMLFormatter()));
  168. try {
  169. setEncoding(manager.getStringProperty(cname +".encoding", null));
  170. } catch (Exception ex) {
  171. try {
  172. setEncoding(null);
  173. } catch (Exception ex2) {
  174. // doing a setEncoding with null should always work.
  175. // assert false;
  176. }
  177. }
  178. }
  179. /**
  180. * Construct a default <tt>FileHandler</tt>. This will be configured
  181. * entirely from <tt>LogManager</tt> properties (or their default values).
  182. * <p>
  183. * @exception IOException if there are IO problems opening the files.
  184. * @exception SecurityException if a security manager exists and if
  185. * the caller does not have <tt>LoggingPermission("control"))</tt>.
  186. */
  187. public FileHandler() throws IOException, SecurityException {
  188. checkAccess();
  189. configure();
  190. openFiles();
  191. }
  192. /**
  193. * Initialize a <tt>FileHandler</tt> to write to the given filename.
  194. * <p>
  195. * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt>
  196. * properties (or their default values) except that the given pattern
  197. * argument is used as the filename pattern, the file limit is
  198. * set to no limit, and the file count is set to one.
  199. * <p>
  200. * There is no limit on the amount of data that may be written,
  201. * so use this with care.
  202. *
  203. * @param pattern the name of the output file
  204. * @exception IOException if there are IO problems opening the files.
  205. * @exception SecurityException if a security manager exists and if
  206. * the caller does not have <tt>LoggingPermission("control")</tt>.
  207. */
  208. public FileHandler(String pattern) throws IOException, SecurityException {
  209. checkAccess();
  210. configure();
  211. this.pattern = pattern;
  212. this.limit = 0;
  213. this.count = 1;
  214. openFiles();
  215. }
  216. /**
  217. * Initialize a <tt>FileHandler</tt> to write to the given filename,
  218. * with optional append.
  219. * <p>
  220. * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt>
  221. * properties (or their default values) except that the given pattern
  222. * argument is used as the filename pattern, the file limit is
  223. * set to no limit, the file count is set to one, and the append
  224. * mode is set to the given <tt>append</tt> argument.
  225. * <p>
  226. * There is no limit on the amount of data that may be written,
  227. * so use this with care.
  228. *
  229. * @param pattern the name of the output file
  230. * @param append specifies append mode
  231. * @exception IOException if there are IO problems opening the files.
  232. * @exception SecurityException if a security manager exists and if
  233. * the caller does not have <tt>LoggingPermission("control")</tt>.
  234. */
  235. public FileHandler(String pattern, boolean append) throws IOException, SecurityException {
  236. checkAccess();
  237. configure();
  238. this.pattern = pattern;
  239. this.limit = 0;
  240. this.count = 1;
  241. this.append = append;
  242. openFiles();
  243. }
  244. /**
  245. * Initialize a <tt>FileHandler</tt> to write to a set of files. When
  246. * (approximately) the given limit has been written to one file,
  247. * another file will be opened. The output will cycle through a set
  248. * of count files.
  249. * <p>
  250. * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt>
  251. * properties (or their default values) except that the given pattern
  252. * argument is used as the filename pattern, the file limit is
  253. * set to the limit argument, and the file count is set to the
  254. * given count argument.
  255. * <p>
  256. * The count must be at least 1.
  257. *
  258. * @param pattern the pattern for naming the output file
  259. * @param limit the maximum number of bytes to write to any one file
  260. * @param count the number of files to use
  261. * @exception IOException if there are IO problems opening the files.
  262. * @exception SecurityException if a security manager exists and if
  263. * the caller does not have <tt>LoggingPermission("control")</tt>.
  264. * @exception IllegalArgumentException if limit < 0, or count < 1.
  265. */
  266. public FileHandler(String pattern, int limit, int count)
  267. throws IOException, SecurityException {
  268. if (limit < 0 || count < 1) {
  269. throw new IllegalArgumentException();
  270. }
  271. checkAccess();
  272. configure();
  273. this.pattern = pattern;
  274. this.limit = limit;
  275. this.count = count;
  276. openFiles();
  277. }
  278. /**
  279. * Initialize a <tt>FileHandler</tt> to write to a set of files
  280. * with optional append. When (approximately) the given limit has
  281. * been written to one file, another file will be opened. The
  282. * output will cycle through a set of count files.
  283. * <p>
  284. * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt>
  285. * properties (or their default values) except that the given pattern
  286. * argument is used as the filename pattern, the file limit is
  287. * set to the limit argument, and the file count is set to the
  288. * given count argument, and the append mode is set to the given
  289. * <tt>append</tt> argument.
  290. * <p>
  291. * The count must be at least 1.
  292. *
  293. * @param pattern the pattern for naming the output file
  294. * @param limit the maximum number of bytes to write to any one file
  295. * @param count the number of files to use
  296. * @param append specifies append mode
  297. * @exception IOException if there are IO problems opening the files.
  298. * @exception SecurityException if a security manager exists and if
  299. * the caller does not have <tt>LoggingPermission("control")</tt>.
  300. * @exception IllegalArgumentException if limit < 0, or count < 1.
  301. *
  302. */
  303. public FileHandler(String pattern, int limit, int count, boolean append)
  304. throws IOException, SecurityException {
  305. if (limit < 0 || count < 1) {
  306. throw new IllegalArgumentException();
  307. }
  308. checkAccess();
  309. configure();
  310. this.pattern = pattern;
  311. this.limit = limit;
  312. this.count = count;
  313. this.append = append;
  314. openFiles();
  315. }
  316. // Private method to open the set of output files, based on the
  317. // configured instance variables.
  318. private void openFiles() throws IOException {
  319. LogManager manager = LogManager.getLogManager();
  320. manager.checkAccess();
  321. if (count < 1) {
  322. throw new IllegalArgumentException("file count = " + count);
  323. }
  324. if (limit < 0) {
  325. limit = 0;
  326. }
  327. // We register our own ErrorManager during initialization
  328. // so we can record exceptions.
  329. InitializationErrorManager em = new InitializationErrorManager();
  330. setErrorManager(em);
  331. // Create a lock file. This grants us exclusive access
  332. // to our set of output files, as long as we are alive.
  333. int unique = -1;
  334. for (;;) {
  335. unique++;
  336. if (unique > MAX_LOCKS) {
  337. throw new IOException("Couldn't get lock for " + pattern);
  338. }
  339. // Generate a lock file name from the "unique" int.
  340. lockFileName = generate(pattern, 0, unique).toString() + ".lck";
  341. // Now try to lock that filename.
  342. // Because some systems (e.g. Solaris) can only do file locks
  343. // between processes (and not within a process), we first check
  344. // if we ourself already have the file locked.
  345. synchronized(locks) {
  346. if (locks.get(lockFileName) != null) {
  347. // We already own this lock, for a different FileHandler
  348. // object. Try again.
  349. continue;
  350. }
  351. FileChannel fc;
  352. try {
  353. lockStream = new FileOutputStream(lockFileName);
  354. fc = lockStream.getChannel();
  355. } catch (IOException ix) {
  356. // We got an IOException while trying to open the file.
  357. // Try the next file.
  358. continue;
  359. }
  360. try {
  361. FileLock fl = fc.tryLock();
  362. if (fl == null) {
  363. // We failed to get the lock. Try next file.
  364. continue;
  365. }
  366. // We got the lock OK.
  367. } catch (IOException ix) {
  368. // We got an IOException while trying to get the lock.
  369. // This normally indicates that locking is not supported
  370. // on the target directory. We have to proceed without
  371. // getting a lock. Drop through.
  372. }
  373. // We got the lock. Remember it.
  374. locks.put(lockFileName, lockFileName);
  375. break;
  376. }
  377. }
  378. files = new File[count];
  379. for (int i = 0; i < count; i++) {
  380. files[i] = generate(pattern, i, unique);
  381. }
  382. // Create the initial log file.
  383. if (append) {
  384. open(files[0], true);
  385. } else {
  386. rotate();
  387. }
  388. // Did we detect any exceptions during initialization?
  389. Exception ex = em.lastException;
  390. if (ex != null) {
  391. if (ex instanceof IOException) {
  392. throw (IOException) ex;
  393. } else if (ex instanceof SecurityException) {
  394. throw (SecurityException) ex;
  395. } else {
  396. throw new IOException("Exception: " + ex);
  397. }
  398. }
  399. // Install the normal default ErrorManager.
  400. setErrorManager(new ErrorManager());
  401. }
  402. // Generate a filename from a pattern.
  403. private File generate(String pattern, int generation, int unique) throws IOException {
  404. File file = null;
  405. String word = "";
  406. int ix = 0;
  407. boolean sawg = false;
  408. boolean sawu = false;
  409. while (ix < pattern.length()) {
  410. char ch = pattern.charAt(ix);
  411. ix++;
  412. char ch2 = 0;
  413. if (ix < pattern.length()) {
  414. ch2 = Character.toLowerCase(pattern.charAt(ix));
  415. }
  416. if (ch == '/') {
  417. if (file == null) {
  418. file = new File(word);
  419. } else {
  420. file = new File(file, word);
  421. }
  422. word = "";
  423. continue;
  424. } else if (ch == '%') {
  425. if (ch2 == 't') {
  426. String tmpDir = System.getProperty("java.io.tmpdir");
  427. if (tmpDir == null) {
  428. tmpDir = System.getProperty("user.home");
  429. }
  430. file = new File(tmpDir);
  431. ix++;
  432. word = "";
  433. continue;
  434. } else if (ch2 == 'h') {
  435. file = new File(System.getProperty("user.home"));
  436. if (isSetUID()) {
  437. // Ok, we are in a set UID program. For safety's sake
  438. // we disallow attempts to open files relative to %h.
  439. throw new IOException("can't use %h in set UID program");
  440. }
  441. ix++;
  442. word = "";
  443. continue;
  444. } else if (ch2 == 'g') {
  445. word = word + generation;
  446. sawg = true;
  447. ix++;
  448. continue;
  449. } else if (ch2 == 'u') {
  450. word = word + unique;
  451. sawu = true;
  452. ix++;
  453. continue;
  454. } else if (ch2 == '%') {
  455. word = word + "%";
  456. ix++;
  457. continue;
  458. }
  459. }
  460. word = word + ch;
  461. }
  462. if (count > 1 && !sawg) {
  463. word = word + "." + generation;
  464. }
  465. if (unique > 0 && !sawu) {
  466. word = word + "." + unique;
  467. }
  468. if (word.length() > 0) {
  469. if (file == null) {
  470. file = new File(word);
  471. } else {
  472. file = new File(file, word);
  473. }
  474. }
  475. return file;
  476. }
  477. // Rotate the set of output files
  478. private synchronized void rotate() {
  479. Level oldLevel = getLevel();
  480. setLevel(Level.OFF);
  481. super.close();
  482. for (int i = count-2; i >= 0; i--) {
  483. File f1 = files[i];
  484. File f2 = files[i+1];
  485. if (f1.exists()) {
  486. if (f2.exists()) {
  487. f2.delete();
  488. }
  489. f1.renameTo(f2);
  490. }
  491. }
  492. try {
  493. open(files[0], false);
  494. } catch (IOException ix) {
  495. // We don't want to throw an exception here, but we
  496. // report the exception to any registered ErrorManager.
  497. reportError(null, ix, ErrorManager.OPEN_FAILURE);
  498. }
  499. setLevel(oldLevel);
  500. }
  501. /**
  502. * Format and publish a <tt>LogRecord</tt>.
  503. *
  504. * @param record description of the log event
  505. */
  506. public synchronized void publish(LogRecord record) {
  507. if (!isLoggable(record)) {
  508. return;
  509. }
  510. super.publish(record);
  511. flush();
  512. if (limit > 0 && meter.written >= limit) {
  513. // We performed access checks in the "init" method to make sure
  514. // we are only initialized from trusted code. So we assume
  515. // it is OK to write the target files, even if we are
  516. // currently being called from untrusted code.
  517. // So it is safe to raise privilege here.
  518. AccessController.doPrivileged(new PrivilegedAction() {
  519. public Object run() {
  520. rotate();
  521. return null;
  522. }
  523. });
  524. }
  525. }
  526. /**
  527. * Close all the files.
  528. *
  529. * @exception SecurityException if a security manager exists and if
  530. * the caller does not have <tt>LoggingPermission("control")</tt>.
  531. */
  532. public synchronized void close() throws SecurityException {
  533. super.close();
  534. // Unlock any lock file.
  535. if (lockFileName == null) {
  536. return;
  537. }
  538. try {
  539. // Closing the lock file's FileOutputStream will close
  540. // the underlying channel and free any locks.
  541. lockStream.close();
  542. } catch (Exception ex) {
  543. // Problems closing the stream. Punt.
  544. }
  545. synchronized(locks) {
  546. locks.remove(lockFileName);
  547. }
  548. lockFileName = null;
  549. lockStream = null;
  550. }
  551. private static class InitializationErrorManager extends ErrorManager {
  552. Exception lastException;
  553. public void error(String msg, Exception ex, int code) {
  554. lastException = ex;
  555. }
  556. }
  557. // Private native method to check if we are in a set UID program.
  558. private static native boolean isSetUID();
  559. }