1 18 package org.objectweb.util.monolog.wrapper.javaLog; 19 20 import org.objectweb.util.monolog.wrapper.common.OutputStreamSwitcher; 21 import org.objectweb.util.monolog.api.BasicLevel; 22 23 import java.io.OutputStream ; 24 import java.io.Writer ; 25 import java.io.OutputStreamWriter ; 26 import java.io.UnsupportedEncodingException ; 27 import java.util.logging.LogRecord ; 28 import java.util.logging.ErrorManager ; 29 30 39 public class ConsoleHandler extends java.util.logging.Handler { 40 41 protected OutputStreamSwitcher oss; 42 private Writer writer; 43 44 public ConsoleHandler() { 45 super(); 46 } 47 48 public void desactivateSwitching(OutputStream newOut) { 49 if (oss != null) { 50 oss = null; 51 setOutput(newOut); 52 } 53 } 54 55 public void activateSwitching() { 56 if (oss == null) { 57 oss = new OutputStreamSwitcher(); 58 setOutput(oss); 59 } 60 } 61 62 66 public void setOutput(OutputStream out) throws SecurityException { 67 if (out == null) { 68 throw new NullPointerException (); 69 } 70 flush(); 71 String encoding = getEncoding(); 72 if (encoding == null) { 73 writer = new OutputStreamWriter (out); 74 } else { 75 try { 76 writer = new OutputStreamWriter (out, encoding); 77 } catch (UnsupportedEncodingException ex) { 78 throw new Error ("Unexpected exception " + ex); 81 } 82 } 83 } 84 85 86 public void publish(LogRecord record) { 87 if (!isLoggable(record)) { 88 return; 89 } 90 String msg; 91 try { 92 msg = getFormatter().format(record); 93 } catch (Exception ex) { 94 reportError(null, ex, ErrorManager.FORMAT_FAILURE); 97 return; 98 } 99 100 if (oss != null) { 101 if (record.getLevel().intValue() >= BasicLevel.WARN) { 102 oss.switchOutput(System.err); 103 } else { 104 oss.switchOutput(System.out); 105 } 106 } 107 try { 108 writer.write(msg); 109 } catch (Exception ex) { 110 reportError(null, ex, ErrorManager.WRITE_FAILURE); 113 } 114 flush(); 115 } 116 117 public void flush() { 118 if (writer != null) { 119 try { 120 writer.flush(); 121 } catch (Exception ex) { 122 reportError(null, ex, ErrorManager.FLUSH_FAILURE); 125 } 126 } 127 } 128 129 public void close() throws SecurityException { 130 flush(); 131 } 132 } | Popular Tags |