1 package ch.qos.logback.core.net;
2
3 import java.io.IOException;
4 import java.io.Writer;
5 import java.net.DatagramPacket;
6 import java.net.DatagramSocket;
7 import java.net.InetAddress;
8 import java.net.SocketException;
9 import java.net.UnknownHostException;
10
11
12
13
14
15 public class SyslogWriter extends Writer {
16
17
18
19
20
21 private static final int MAX_LEN = 1024;
22
23 private InetAddress address;
24 private DatagramSocket ds;
25 private StringBuffer buf = new StringBuffer();
26 final private int port;
27
28 public SyslogWriter(String syslogHost, int port) throws UnknownHostException,
29 SocketException {
30 this.address = InetAddress.getByName(syslogHost);
31 this.port = port;
32 this.ds = new DatagramSocket();
33 }
34
35 public void write(char[] charArray, int offset, int len) throws IOException {
36 buf.append(charArray, offset, len);
37 }
38
39 public void write(String str) throws IOException {
40 buf.append(str);
41
42 }
43
44 public void flush() throws IOException {
45 byte[] bytes = buf.toString().getBytes();
46 DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address,
47 port);
48
49 if (this.ds != null) {
50 ds.send(packet);
51 }
52
53 if (buf.length() > MAX_LEN) {
54 buf = new StringBuffer();
55 } else {
56 buf.setLength(0);
57 }
58 }
59
60 public void close() {
61 address = null;
62 ds = null;
63 }
64
65 public int getPort() {
66 return port;
67 }
68
69 }