1 /* 2 * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.util.logging; 27 28 import static java.nio.file.StandardOpenOption.APPEND; 29 import static java.nio.file.StandardOpenOption.CREATE_NEW; 30 import static java.nio.file.StandardOpenOption.WRITE; 31 32 import java.io.BufferedOutputStream; 33 import java.io.File; 34 import java.io.FileNotFoundException; 35 import java.io.FileOutputStream; 36 import java.io.IOException; 37 import java.io.OutputStream; 38 import java.nio.channels.FileChannel; 39 import java.nio.channels.OverlappingFileLockException; 40 import java.nio.file.FileAlreadyExistsException; 41 import java.nio.file.Files; 42 import java.nio.file.LinkOption; 43 import java.nio.file.Path; 44 import java.nio.file.Paths; 45 import java.security.AccessController; 46 import java.security.PrivilegedAction; 47 import java.util.HashSet; 48 import java.util.Set; 49 50 /** 51 * Simple file logging <tt>Handler</tt>. 52 * <p> 53 * The <tt>FileHandler</tt> can either write to a specified file, 54 * or it can write to a rotating set of files. 55 * <p> 56 * For a rotating set of files, as each file reaches a given size 57 * limit, it is closed, rotated out, and a new file opened. 58 * Successively older files are named by adding "0", "1", "2", 59 * etc. into the base filename. 60 * <p> 61 * By default buffering is enabled in the IO libraries but each log 62 * record is flushed out when it is complete. 63 * <p> 64 * By default the <tt>XMLFormatter</tt> class is used for formatting. 65 * <p> 66 * <b>Configuration:</b> 67 * By default each <tt>FileHandler</tt> is initialized using the following 68 * <tt>LogManager</tt> configuration properties where <tt><handler-name></tt> 69 * refers to the fully-qualified class name of the handler. 70 * If properties are not defined 71 * (or have invalid values) then the specified default values are used. 72 * <ul> 73 * <li> <handler-name>.level 74 * specifies the default level for the <tt>Handler</tt> 75 * (defaults to <tt>Level.ALL</tt>). </li> 76 * <li> <handler-name>.filter 77 * specifies the name of a <tt>Filter</tt> class to use 78 * (defaults to no <tt>Filter</tt>). </li> 79 * <li> <handler-name>.formatter 80 * specifies the name of a <tt>Formatter</tt> class to use 81 * (defaults to <tt>java.util.logging.XMLFormatter</tt>) </li> 82 * <li> <handler-name>.encoding 83 * the name of the character set encoding to use (defaults to 84 * the default platform encoding). </li> 85 * <li> <handler-name>.limit 86 * specifies an approximate maximum amount to write (in bytes) 87 * to any one file. If this is zero, then there is no limit. 88 * (Defaults to no limit). </li> 89 * <li> <handler-name>.count 90 * specifies how many output files to cycle through (defaults to 1). </li> 91 * <li> <handler-name>.pattern 92 * specifies a pattern for generating the output file name. See 93 * below for details. (Defaults to "%h/java%u.log"). </li> 94 * <li> <handler-name>.append 95 * specifies whether the FileHandler should append onto 96 * any existing files (defaults to false). </li> 97 * </ul> 98 * <p> 99 * For example, the properties for {@code FileHandler} would be: 100 * <ul> 101 * <li> java.util.logging.FileHandler.level=INFO </li> 102 * <li> java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter </li> 103 * </ul> 104 * <p> 105 * For a custom handler, e.g. com.foo.MyHandler, the properties would be: 106 * <ul> 107 * <li> com.foo.MyHandler.level=INFO </li> 108 * <li> com.foo.MyHandler.formatter=java.util.logging.SimpleFormatter </li> 109 * </ul> 110 * <p> 111 * A pattern consists of a string that includes the following special 112 * components that will be replaced at runtime: 113 * <ul> 114 * <li> "/" the local pathname separator </li> 115 * <li> "%t" the system temporary directory </li> 116 * <li> "%h" the value of the "user.home" system property </li> 117 * <li> "%g" the generation number to distinguish rotated logs </li> 118 * <li> "%u" a unique number to resolve conflicts </li> 119 * <li> "%%" translates to a single percent sign "%" </li> 120 * </ul> 121 * If no "%g" field has been specified and the file count is greater 122 * than one, then the generation number will be added to the end of 123 * the generated filename, after a dot. 124 * <p> 125 * Thus for example a pattern of "%t/java%g.log" with a count of 2 126 * would typically cause log files to be written on Solaris to 127 * /var/tmp/java0.log and /var/tmp/java1.log whereas on Windows 95 they 128 * would be typically written to C:\TEMP\java0.log and C:\TEMP\java1.log 129 * <p> 130 * Generation numbers follow the sequence 0, 1, 2, etc. 131 * <p> 132 * Normally the "%u" unique field is set to 0. However, if the <tt>FileHandler</tt> 133 * tries to open the filename and finds the file is currently in use by 134 * another process it will increment the unique number field and try 135 * again. This will be repeated until <tt>FileHandler</tt> finds a file name that 136 * is not currently in use. If there is a conflict and no "%u" field has 137 * been specified, it will be added at the end of the filename after a dot. 138 * (This will be after any automatically added generation number.) 139 * <p> 140 * Thus if three processes were all trying to log to fred%u.%g.txt then 141 * they might end up using fred0.0.txt, fred1.0.txt, fred2.0.txt as 142 * the first file in their rotating sequences. 143 * <p> 144 * Note that the use of unique ids to avoid conflicts is only guaranteed 145 * to work reliably when using a local disk file system. 146 * 147 * @since 1.4 148 */ 149 150 public class FileHandler extends StreamHandler { 151 private MeteredStream meter; 152 private boolean append; 153 private int limit; // zero => no limit. 154 private int count; 155 private String pattern; 156 private String lockFileName; 157 private FileChannel lockFileChannel; 158 private File files[]; 159 private static final int MAX_LOCKS = 100; 160 private static final Set<String> locks = new HashSet<>(); 161 162 /** 163 * A metered stream is a subclass of OutputStream that 164 * (a) forwards all its output to a target stream 165 * (b) keeps track of how many bytes have been written 166 */ 167 private class MeteredStream extends OutputStream { 168 final OutputStream out; 169 int written; 170 171 MeteredStream(OutputStream out, int written) { 172 this.out = out; 173 this.written = written; 174 } 175 176 @Override 177 public void write(int b) throws IOException { 178 out.write(b); 179 written++; 180 } 181 182 @Override 183 public void write(byte buff[]) throws IOException { 184 out.write(buff); 185 written += buff.length; 186 } 187 188 @Override 189 public void write(byte buff[], int off, int len) throws IOException { 190 out.write(buff,off,len); 191 written += len; 192 } 193 194 @Override 195 public void flush() throws IOException { 196 out.flush(); 197 } 198 199 @Override 200 public void close() throws IOException { 201 out.close(); 202 } 203 } 204 205 private void open(File fname, boolean append) throws IOException { 206 int len = 0; 207 if (append) { 208 len = (int)fname.length(); 209 } 210 FileOutputStream fout = new FileOutputStream(fname.toString(), append); 211 BufferedOutputStream bout = new BufferedOutputStream(fout); 212 meter = new MeteredStream(bout, len); 213 setOutputStream(meter); 214 } 215 216 /** 217 * Configure a FileHandler from LogManager properties and/or default values 218 * as specified in the class javadoc. 219 */ 220 private void configure() { 221 LogManager manager = LogManager.getLogManager(); 222 223 String cname = getClass().getName(); 224 225 pattern = manager.getStringProperty(cname + ".pattern", "%h/java%u.log"); 226 limit = manager.getIntProperty(cname + ".limit", 0); 227 if (limit < 0) { 228 limit = 0; 229 } 230 count = manager.getIntProperty(cname + ".count", 1); 231 if (count <= 0) { 232 count = 1; 233 } 234 append = manager.getBooleanProperty(cname + ".append", false); 235 setLevel(manager.getLevelProperty(cname + ".level", Level.ALL)); 236 setFilter(manager.getFilterProperty(cname + ".filter", null)); 237 setFormatter(manager.getFormatterProperty(cname + ".formatter", new XMLFormatter())); 238 try { 239 setEncoding(manager.getStringProperty(cname +".encoding", null)); 240 } catch (Exception ex) { 241 try { 242 setEncoding(null); 243 } catch (Exception ex2) { 244 // doing a setEncoding with null should always work. 245 // assert false; 246 } 247 } 248 } 249 250 251 /** 252 * Construct a default <tt>FileHandler</tt>. This will be configured 253 * entirely from <tt>LogManager</tt> properties (or their default values). 254 * 255 * @exception IOException if there are IO problems opening the files. 256 * @exception SecurityException if a security manager exists and if 257 * the caller does not have <tt>LoggingPermission("control"))</tt>. 258 * @exception NullPointerException if pattern property is an empty String. 259 */ 260 public FileHandler() throws IOException, SecurityException { 261 checkPermission(); 262 configure(); 263 openFiles(); 264 } 265 266 /** 267 * Initialize a <tt>FileHandler</tt> to write to the given filename. 268 * <p> 269 * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt> 270 * properties (or their default values) except that the given pattern 271 * argument is used as the filename pattern, the file limit is 272 * set to no limit, and the file count is set to one. 273 * <p> 274 * There is no limit on the amount of data that may be written, 275 * so use this with care. 276 * 277 * @param pattern the name of the output file 278 * @exception IOException if there are IO problems opening the files. 279 * @exception SecurityException if a security manager exists and if 280 * the caller does not have <tt>LoggingPermission("control")</tt>. 281 * @exception IllegalArgumentException if pattern is an empty string 282 */ 283 public FileHandler(String pattern) throws IOException, SecurityException { 284 if (pattern.length() < 1 ) { 285 throw new IllegalArgumentException(); 286 } 287 checkPermission(); 288 configure(); 289 this.pattern = pattern; 290 this.limit = 0; 291 this.count = 1; 292 openFiles(); 293 } 294 295 /** 296 * Initialize a <tt>FileHandler</tt> to write to the given filename, 297 * with optional append. 298 * <p> 299 * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt> 300 * properties (or their default values) except that the given pattern 301 * argument is used as the filename pattern, the file limit is 302 * set to no limit, the file count is set to one, and the append 303 * mode is set to the given <tt>append</tt> argument. 304 * <p> 305 * There is no limit on the amount of data that may be written, 306 * so use this with care. 307 * 308 * @param pattern the name of the output file 309 * @param append specifies append mode 310 * @exception IOException if there are IO problems opening the files. 311 * @exception SecurityException if a security manager exists and if 312 * the caller does not have <tt>LoggingPermission("control")</tt>. 313 * @exception IllegalArgumentException if pattern is an empty string 314 */ 315 public FileHandler(String pattern, boolean append) throws IOException, 316 SecurityException { 317 if (pattern.length() < 1 ) { 318 throw new IllegalArgumentException(); 319 } 320 checkPermission(); 321 configure(); 322 this.pattern = pattern; 323 this.limit = 0; 324 this.count = 1; 325 this.append = append; 326 openFiles(); 327 } 328 329 /** 330 * Initialize a <tt>FileHandler</tt> to write to a set of files. When 331 * (approximately) the given limit has been written to one file, 332 * another file will be opened. The output will cycle through a set 333 * of count files. 334 * <p> 335 * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt> 336 * properties (or their default values) except that the given pattern 337 * argument is used as the filename pattern, the file limit is 338 * set to the limit argument, and the file count is set to the 339 * given count argument. 340 * <p> 341 * The count must be at least 1. 342 * 343 * @param pattern the pattern for naming the output file 344 * @param limit the maximum number of bytes to write to any one file 345 * @param count the number of files to use 346 * @exception IOException if there are IO problems opening the files. 347 * @exception SecurityException if a security manager exists and if 348 * the caller does not have <tt>LoggingPermission("control")</tt>. 349 * @exception IllegalArgumentException if {@code limit < 0}, or {@code count < 1}. 350 * @exception IllegalArgumentException if pattern is an empty string 351 */ 352 public FileHandler(String pattern, int limit, int count) 353 throws IOException, SecurityException { 354 if (limit < 0 || count < 1 || pattern.length() < 1) { 355 throw new IllegalArgumentException(); 356 } 357 checkPermission(); 358 configure(); 359 this.pattern = pattern; 360 this.limit = limit; 361 this.count = count; 362 openFiles(); 363 } 364 365 /** 366 * Initialize a <tt>FileHandler</tt> to write to a set of files 367 * with optional append. When (approximately) the given limit has 368 * been written to one file, another file will be opened. The 369 * output will cycle through a set of count files. 370 * <p> 371 * The <tt>FileHandler</tt> is configured based on <tt>LogManager</tt> 372 * properties (or their default values) except that the given pattern 373 * argument is used as the filename pattern, the file limit is 374 * set to the limit argument, and the file count is set to the 375 * given count argument, and the append mode is set to the given 376 * <tt>append</tt> argument. 377 * <p> 378 * The count must be at least 1. 379 * 380 * @param pattern the pattern for naming the output file 381 * @param limit the maximum number of bytes to write to any one file 382 * @param count the number of files to use 383 * @param append specifies append mode 384 * @exception IOException if there are IO problems opening the files. 385 * @exception SecurityException if a security manager exists and if 386 * the caller does not have <tt>LoggingPermission("control")</tt>. 387 * @exception IllegalArgumentException if {@code limit < 0}, or {@code count < 1}. 388 * @exception IllegalArgumentException if pattern is an empty string 389 * 390 */ 391 public FileHandler(String pattern, int limit, int count, boolean append) 392 throws IOException, SecurityException { 393 if (limit < 0 || count < 1 || pattern.length() < 1) { 394 throw new IllegalArgumentException(); 395 } 396 checkPermission(); 397 configure(); 398 this.pattern = pattern; 399 this.limit = limit; 400 this.count = count; 401 this.append = append; 402 openFiles(); 403 } 404 405 /** 406 * Open the set of output files, based on the configured 407 * instance variables. 408 */ 409 private void openFiles() throws IOException { 410 LogManager manager = LogManager.getLogManager(); 411 manager.checkPermission(); 412 if (count < 1) { 413 throw new IllegalArgumentException("file count = " + count); 414 } 415 if (limit < 0) { 416 limit = 0; 417 } 418 419 // We register our own ErrorManager during initialization 420 // so we can record exceptions. 421 InitializationErrorManager em = new InitializationErrorManager(); 422 setErrorManager(em); 423 424 // Create a lock file. This grants us exclusive access 425 // to our set of output files, as long as we are alive. 426 int unique = -1; 427 for (;;) { 428 unique++; 429 if (unique > MAX_LOCKS) { 430 throw new IOException("Couldn't get lock for " + pattern); 431 } 432 // Generate a lock file name from the "unique" int. 433 lockFileName = generate(pattern, 0, unique).toString() + ".lck"; 434 // Now try to lock that filename. 435 // Because some systems (e.g., Solaris) can only do file locks 436 // between processes (and not within a process), we first check 437 // if we ourself already have the file locked. 438 synchronized(locks) { 439 if (locks.contains(lockFileName)) { 440 // We already own this lock, for a different FileHandler 441 // object. Try again. 442 continue; 443 } 444 445 final Path lockFilePath = Paths.get(lockFileName); 446 FileChannel channel = null; 447 int retries = -1; 448 boolean fileCreated = false; 449 while (channel == null && retries++ < 1) { 450 try { 451 channel = FileChannel.open(lockFilePath, 452 CREATE_NEW, WRITE); 453 fileCreated = true; 454 } catch (FileAlreadyExistsException ix) { 455 // This may be a zombie file left over by a previous 456 // execution. Reuse it - but only if we can actually 457 // write to its directory. 458 // Note that this is a situation that may happen, 459 // but not too frequently. 460 if (Files.isRegularFile(lockFilePath, LinkOption.NOFOLLOW_LINKS) 461 && Files.isWritable(lockFilePath.getParent())) { 462 try { 463 channel = FileChannel.open(lockFilePath, 464 WRITE, APPEND); 465 } catch (FileNotFoundException x) { 466 // Race condition - retry once, and if that 467 // fails again just try the next name in 468 // the sequence. 469 continue; 470 } 471 } else { 472 // at this point channel should still be null. 473 // break and try the next name in the sequence. 474 break; 475 } 476 } 477 } 478 479 if (channel == null) continue; // try the next name; 480 lockFileChannel = channel; 481 482 boolean available; 483 try { 484 available = lockFileChannel.tryLock() != null; 485 // We got the lock OK. 486 // At this point we could call File.deleteOnExit(). 487 // However, this could have undesirable side effects 488 // as indicated by JDK-4872014. So we will instead 489 // rely on the fact that close() will remove the lock 490 // file and that whoever is creating FileHandlers should 491 // be responsible for closing them. 492 } catch (IOException ix) { 493 // We got an IOException while trying to get the lock. 494 // This normally indicates that locking is not supported 495 // on the target directory. We have to proceed without 496 // getting a lock. Drop through, but only if we did 497 // create the file... 498 available = fileCreated; 499 } catch (OverlappingFileLockException x) { 500 // someone already locked this file in this VM, through 501 // some other channel - that is - using something else 502 // than new FileHandler(...); 503 // continue searching for an available lock. 504 available = false; 505 } 506 if (available) { 507 // We got the lock. Remember it. 508 locks.add(lockFileName); 509 break; 510 } 511 512 // We failed to get the lock. Try next file. 513 lockFileChannel.close(); 514 } 515 } 516 517 files = new File[count]; 518 for (int i = 0; i < count; i++) { 519 files[i] = generate(pattern, i, unique); 520 } 521 522 // Create the initial log file. 523 if (append) { 524 open(files[0], true); 525 } else { 526 rotate(); 527 } 528 529 // Did we detect any exceptions during initialization? 530 Exception ex = em.lastException; 531 if (ex != null) { 532 if (ex instanceof IOException) { 533 throw (IOException) ex; 534 } else if (ex instanceof SecurityException) { 535 throw (SecurityException) ex; 536 } else { 537 throw new IOException("Exception: " + ex); 538 } 539 } 540 541 // Install the normal default ErrorManager. 542 setErrorManager(new ErrorManager()); 543 } 544 545 /** 546 * Generate a file based on a user-supplied pattern, generation number, 547 * and an integer uniqueness suffix 548 * @param pattern the pattern for naming the output file 549 * @param generation the generation number to distinguish rotated logs 550 * @param unique a unique number to resolve conflicts 551 * @return the generated File 552 * @throws IOException 553 */ 554 private File generate(String pattern, int generation, int unique) 555 throws IOException { 556 File file = null; 557 String word = ""; 558 int ix = 0; 559 boolean sawg = false; 560 boolean sawu = false; 561 while (ix < pattern.length()) { 562 char ch = pattern.charAt(ix); 563 ix++; 564 char ch2 = 0; 565 if (ix < pattern.length()) { 566 ch2 = Character.toLowerCase(pattern.charAt(ix)); 567 } 568 if (ch == '/') { 569 if (file == null) { 570 file = new File(word); 571 } else { 572 file = new File(file, word); 573 } 574 word = ""; 575 continue; 576 } else if (ch == '%') { 577 if (ch2 == 't') { 578 String tmpDir = System.getProperty("java.io.tmpdir"); 579 if (tmpDir == null) { 580 tmpDir = System.getProperty("user.home"); 581 } 582 file = new File(tmpDir); 583 ix++; 584 word = ""; 585 continue; 586 } else if (ch2 == 'h') { 587 file = new File(System.getProperty("user.home")); 588 if (sun.misc.VM.isSetUID()) { 589 // Ok, we are in a set UID program. For safety's sake 590 // we disallow attempts to open files relative to %h. 591 throw new IOException("can't use %h in set UID program"); 592 } 593 ix++; 594 word = ""; 595 continue; 596 } else if (ch2 == 'g') { 597 word = word + generation; 598 sawg = true; 599 ix++; 600 continue; 601 } else if (ch2 == 'u') { 602 word = word + unique; 603 sawu = true; 604 ix++; 605 continue; 606 } else if (ch2 == '%') { 607 word = word + "%"; 608 ix++; 609 continue; 610 } 611 } 612 word = word + ch; 613 } 614 if (count > 1 && !sawg) { 615 word = word + "." + generation; 616 } 617 if (unique > 0 && !sawu) { 618 word = word + "." + unique; 619 } 620 if (word.length() > 0) { 621 if (file == null) { 622 file = new File(word); 623 } else { 624 file = new File(file, word); 625 } 626 } 627 return file; 628 } 629 630 /** 631 * Rotate the set of output files 632 */ 633 private synchronized void rotate() { 634 Level oldLevel = getLevel(); 635 setLevel(Level.OFF); 636 637 super.close(); 638 for (int i = count-2; i >= 0; i--) { 639 File f1 = files[i]; 640 File f2 = files[i+1]; 641 if (f1.exists()) { 642 if (f2.exists()) { 643 f2.delete(); 644 } 645 f1.renameTo(f2); 646 } 647 } 648 try { 649 open(files[0], false); 650 } catch (IOException ix) { 651 // We don't want to throw an exception here, but we 652 // report the exception to any registered ErrorManager. 653 reportError(null, ix, ErrorManager.OPEN_FAILURE); 654 655 } 656 setLevel(oldLevel); 657 } 658 659 /** 660 * Format and publish a <tt>LogRecord</tt>. 661 * 662 * @param record description of the log event. A null record is 663 * silently ignored and is not published 664 */ 665 @Override 666 public synchronized void publish(LogRecord record) { 667 if (!isLoggable(record)) { 668 return; 669 } 670 super.publish(record); 671 flush(); 672 if (limit > 0 && meter.written >= limit) { 673 // We performed access checks in the "init" method to make sure 674 // we are only initialized from trusted code. So we assume 675 // it is OK to write the target files, even if we are 676 // currently being called from untrusted code. 677 // So it is safe to raise privilege here. 678 AccessController.doPrivileged(new PrivilegedAction<Object>() { 679 @Override 680 public Object run() { 681 rotate(); 682 return null; 683 } 684 }); 685 } 686 } 687 688 /** 689 * Close all the files. 690 * 691 * @exception SecurityException if a security manager exists and if 692 * the caller does not have <tt>LoggingPermission("control")</tt>. 693 */ 694 @Override 695 public synchronized void close() throws SecurityException { 696 super.close(); 697 // Unlock any lock file. 698 if (lockFileName == null) { 699 return; 700 } 701 try { 702 // Close the lock file channel (which also will free any locks) 703 lockFileChannel.close(); 704 } catch (Exception ex) { 705 // Problems closing the stream. Punt. 706 } 707 synchronized(locks) { 708 locks.remove(lockFileName); 709 } 710 new File(lockFileName).delete(); 711 lockFileName = null; 712 lockFileChannel = null; 713 } 714 715 private static class InitializationErrorManager extends ErrorManager { 716 Exception lastException; 717 @Override 718 public void error(String msg, Exception ex, int code) { 719 lastException = ex; 720 } 721 } 722 }