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