Posted By

robyy on 06/14/12



Versions (?)


 / Published in: Java

Now you are ready to log to your heart’s content. Keep in mind that all messages with level INFO, WARNING, and SEVERE show up on the console. Therefore, reserve these levels for messages that are meaningful to the users of your program. The level FINE is a good choice for logging messages that are intended for programmers. Whenever you are tempted to call System.out.println, emit a log message instead: logger.fine("File open dialog canceled"); It is also a good idea to log unexpected exceptions. For example: try { . . . } catch (SomeException e) { logger.log(Level.FINE, "explanation", e); }

  1. //The following code ensures that all messages are logged to an application-//specific file. Place the code into the main method of your application.
  2. if (System.getProperty("java.util.logging.config.class") == null
  3. && System.getProperty("java.util.logging.config.file") == null)
  4. {
  5. try
  6. {
  7. Logger.getLogger("").setLevel(Level.ALL);
  8. final int LOG_ROTATION_COUNT = 10;
  9. Handler handler = new FileHandler("%h/myapp.log", 0, LOG_ROTATION_COUNT);
  10. Logger.getLogger("").addHandler(handler); // 同一个logger可以添加多个不同的handler
  11. }
  12. catch (IOException e)
  13. {
  14. logger.log(Level.SEVERE, "Can't create log file handler", e);
  15. }
  16. }

Report this snippet  

You need to login to post a comment.