1 28 29 package com.caucho.log; 30 31 import com.caucho.server.util.CauchoSystem; 32 import com.caucho.util.Alarm; 33 import com.caucho.util.QDate; 34 import com.caucho.vfs.Path; 35 import com.caucho.vfs.StreamImpl; 36 import com.caucho.vfs.WriteStream; 37 38 import java.io.IOException ; 39 40 44 public class TimestampFilter extends StreamImpl { 45 private WriteStream _stream; 46 47 private String _timestamp; 48 49 private QDate _calendar = new QDate(true); 50 51 private boolean _isLineBegin = true; 52 53 58 public TimestampFilter() 59 { 60 } 61 62 67 public TimestampFilter(WriteStream out, String timestamp) 68 { 69 _stream = out; 70 _timestamp = timestamp; 71 } 72 73 public void setTimestamp(String timestamp) 74 { 75 _timestamp = timestamp; 76 } 77 78 public void setStream(WriteStream stream) 79 { 80 _stream = stream; 81 } 82 83 public Path getPath() 84 { 85 if (_stream != null) 86 return _stream.getPath(); 87 else 88 return super.getPath(); 89 } 90 91 94 public boolean canWrite() 95 { 96 return _stream != null && _stream.canWrite(); 97 } 98 99 102 public void write(byte []buffer, int offset, int length, boolean isEnd) 103 throws IOException 104 { 105 if (_stream == null) 106 return; 107 108 if (_timestamp == null) { 109 _stream.write(buffer, offset, length); 110 return; 111 } 112 113 long now; 114 115 if (CauchoSystem.isTesting()) 116 now = Alarm.getCurrentTime(); 117 else 118 now = System.currentTimeMillis(); 119 120 for (int i = 0; i < length; i++) { 121 if (_isLineBegin) { 122 _stream.print(_calendar.formatLocal(now, _timestamp)); 123 _isLineBegin = false; 124 } 125 126 int ch = buffer[offset + i]; 127 _stream.write(ch); 128 129 if (ch == '\n' || 130 ch == '\r' && i + 1 < length && buffer[offset + i + 1] != '\n') 131 _isLineBegin = true; 132 } 133 } 134 135 138 public void flush() 139 throws IOException 140 { 141 if (_stream != null) 142 _stream.flush(); 143 } 144 145 148 public void close() 149 throws IOException 150 { 151 if (_stream != null) 152 _stream.close(); 153 } 154 } 155 | Popular Tags |