1 2 import java.util.logging.Logger ; 3 import java.util.logging.LogManager ; 4 import java.util.logging.Level ; 5 import java.util.logging.Handler ; 6 import java.io.*; 7 8 14 public class SimpleLoggingApp 15 { 16 private static final Logger log = Logger.getLogger(SimpleLoggingApp.class.getName()); 17 private static final Logger root = Logger.getLogger(""); 18 19 public static void main(String [] args) throws java.io.IOException 20 { 21 LogManager.getLogManager().readConfiguration(getLoggingConfiguration()); 25 26 log.finest("This is a finest message"); 27 log.finer("This is a finer message"); 28 log.fine("This is a fine message"); 29 log.config("This is a config message"); 30 31 Handler [] handlers = root.getHandlers(); 32 StringBuffer sbHandlers = new StringBuffer (); 33 sbHandlers.append("Root logger handlers: "); 34 35 if (handlers.length < 1) 36 { 37 sbHandlers.append("none"); 38 } 39 else 40 { 41 for (int i = 0; i < handlers.length; i++) 42 { 43 sbHandlers.append(handlers[i].getClass().getName()); 44 if (i < (handlers.length - 1)) 45 { 46 sbHandlers.append(", "); 47 } 48 } 49 } 50 log.config(sbHandlers.toString()); 51 52 log.info("This is an info message"); 53 log.warning("This is a warning message"); 54 log.severe("This is a severe message"); 55 56 try 57 { 58 String nullObject = null; 59 nullObject.toString(); 60 } 61 catch (Exception ex) 62 { 63 log.log(Level.SEVERE, "caught an exception", ex); 64 } 65 } 66 67 static private java.io.InputStream getLoggingConfiguration() 68 { 69 StringBuffer sb = new StringBuffer (); 70 71 sb.append("handlers=java.util.logging.ConsoleHandler,smtphandler.SMTPHandler"); 72 sb.append("\n"); 73 sb.append(".level= FINEST"); 74 sb.append("\n"); 75 76 sb.append("java.util.logging.ConsoleHandler.level=FINEST"); 78 sb.append("\n"); 79 sb.append("java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter"); 80 sb.append("\n"); 81 82 sb.append("smtphandler.SMTPHandler.level=WARNING"); 84 sb.append("\n"); 85 sb.append("smtphandler.SMTPHandler.smtpHost=127.0.0.1"); 86 sb.append("\n"); 87 sb.append("smtphandler.SMTPHandler.to=neo@localhost"); 88 sb.append("\n"); 89 sb.append("smtphandler.SMTPHandler.from=appserver@server3"); 90 sb.append("\n"); 91 sb.append("smtphandler.SMTPHandler.subject=[SMTPHandler] Message from SimpleApp"); 92 sb.append("\n"); 93 sb.append("smtphandler.SMTPHandler.bufferSize=512"); 94 sb.append("\n"); 95 sb.append("smtphandler.SMTPHandler.formatter=java.util.logging.SimpleFormatter"); 96 sb.append("\n"); 97 98 InputStream is = new ByteArrayInputStream(sb.toString().getBytes()); 99 100 return is; 101 } 102 } 103 | Popular Tags |