1 16 17 package org.apache.log4j.net; 18 19 import java.io.Writer ; 20 import java.net.DatagramSocket ; 21 import java.net.InetAddress ; 22 import java.net.DatagramPacket ; 23 import java.net.UnknownHostException ; 24 import java.net.SocketException ; 25 import java.io.IOException ; 26 27 import org.apache.log4j.helpers.LogLog; 28 29 33 public class DatagramStringWriter extends Writer { 34 35 static final int SYSLOG_PORT = 514; 36 37 private int port; 38 private String host; 39 private String encoding; 40 private String prefix; 41 42 private InetAddress address; 43 private DatagramSocket ds; 44 45 50 public 51 DatagramStringWriter(String host) { 52 this(host, SYSLOG_PORT, null, null); 53 } 54 55 60 public 61 DatagramStringWriter(String host, int port) { 62 this(host, port, null, null); 63 } 64 65 70 public 71 DatagramStringWriter(String host, int port, String encoding) { 72 this(host, port, null, null); 73 } 74 80 public 81 DatagramStringWriter(String host, int port, String encoding, String prefix) { 82 this.host = host; 83 this.port = port; 84 this.encoding = encoding; 85 this.prefix = prefix; 86 87 try { 88 this.address = InetAddress.getByName(host); 89 } 90 catch (UnknownHostException e) { 91 LogLog.error("Could not find " + host + 92 ". All logging will FAIL.", e); 93 } 94 95 try { 96 this.ds = new DatagramSocket (); 97 } 98 catch (SocketException e) { 99 e.printStackTrace(); 100 LogLog.error("Could not instantiate DatagramSocket to " + host + 101 ". All logging will FAIL.", e); 102 } 103 } 104 105 106 public 107 void write(char[] buf, int off, int len) throws IOException { 108 this.write(new String (buf, off, len)); 109 } 110 111 public 112 void write(String string) throws IOException { 113 if (prefix != null) { 114 string = prefix + string; 115 } 116 117 byte[] rawData; 118 if (this.encoding == null) 119 { 120 rawData = string.getBytes(); 122 } 123 else 124 { 125 rawData = string.getBytes(encoding); 130 } 131 132 DatagramPacket packet = 133 new DatagramPacket ( 134 rawData, 135 rawData.length, 136 address, 137 port); 138 139 if(this.ds != null) 140 { 141 ds.send(packet); 142 } 143 else 144 { 145 LogLog.error( 146 "write: failed to create DatagramPacket"); 147 } 148 } 149 150 public 151 void flush() {} 152 153 public 154 void close() {} 155 156 168 public 169 void setPrefix(String prefix){ 170 this.prefix = prefix; 171 } 172 } 173 | Popular Tags |