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