1 22 39 package org.objectweb.petals.util.monolog.wrapper.javalog; 40 41 import java.io.OutputStream ; 42 import java.io.OutputStreamWriter ; 43 import java.io.UnsupportedEncodingException ; 44 import java.io.Writer ; 45 import java.util.logging.ErrorManager ; 46 import java.util.logging.LogRecord ; 47 48 import org.objectweb.util.monolog.api.BasicLevel; 49 import org.objectweb.util.monolog.wrapper.common.OutputStreamSwitcher; 50 51 61 public class ConsoleHandler extends java.util.logging.Handler { 62 63 protected OutputStreamSwitcher oss; 64 65 private Writer writer; 66 67 public ConsoleHandler() { 68 super(); 69 } 70 71 public void activateSwitching() { 72 if (oss == null) { 73 oss = new OutputStreamSwitcher(); 74 setOutput(oss); 75 } 76 } 77 78 public void close() throws SecurityException { 79 flush(); 80 } 81 82 public void desactivateSwitching(OutputStream newOut) { 83 if (oss != null) { 84 oss = null; 85 setOutput(newOut); 86 } 87 } 88 89 public void flush() { 90 if (writer != null) { 91 try { 92 writer.flush(); 93 } catch (Exception ex) { 94 reportError(null, ex, ErrorManager.FLUSH_FAILURE); 97 } 98 } 99 } 100 101 public void publish(LogRecord record) { 102 if (!isLoggable(record)) { 103 return; 104 } 105 String msg; 106 try { 107 msg = getFormatter().format(record); 108 } catch (Exception ex) { 109 reportError(null, ex, ErrorManager.FORMAT_FAILURE); 112 return; 113 } 114 115 if (oss != null) { 116 if (record.getLevel().intValue() >= BasicLevel.WARN) { 117 oss.switchOutput(System.err); 118 } else { 119 oss.switchOutput(System.out); 120 } 121 } 122 try { 123 writer.write(msg); 124 } catch (Exception ex) { 125 reportError(null, ex, ErrorManager.WRITE_FAILURE); 128 } 129 flush(); 130 } 131 132 136 public void setOutput(OutputStream out) throws SecurityException { 137 if (out == null) { 138 throw new NullPointerException (); 139 } 140 flush(); 141 String encoding = getEncoding(); 142 if (encoding == null) { 143 writer = new OutputStreamWriter (out); 144 } else { 145 try { 146 writer = new OutputStreamWriter (out, encoding); 147 } catch (UnsupportedEncodingException ex) { 148 throw new Error ("Unexpected exception " + ex); 151 } 152 } 153 } 154 } | Popular Tags |