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.ByteArrayOutputStream;
17 import java.io.IOException;
18 import java.io.OutputStream;
19 import java.net.DatagramPacket;
20 import java.net.DatagramSocket;
21 import java.net.InetAddress;
22 import java.net.SocketException;
23 import java.net.UnknownHostException;
24
25
26
27
28
29 public class SyslogOutputStream extends OutputStream {
30
31
32
33
34
35 private static final int MAX_LEN = 1024;
36
37 private InetAddress address;
38 private DatagramSocket ds;
39 private ByteArrayOutputStream baos = new ByteArrayOutputStream();
40 final private int port;
41
42 public SyslogOutputStream(String syslogHost, int port) throws UnknownHostException, SocketException {
43 this.address = InetAddress.getByName(syslogHost);
44 this.port = port;
45 this.ds = new DatagramSocket();
46 }
47
48 public void write(byte[] byteArray, int offset, int len) throws IOException {
49 baos.write(byteArray, offset, len);
50 }
51
52 public void flush() throws IOException {
53 byte[] bytes = baos.toByteArray();
54 DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port);
55
56
57 if (baos.size() > MAX_LEN) {
58 baos = new ByteArrayOutputStream();
59 } else {
60 baos.reset();
61 }
62
63
64
65 if (bytes.length == 0) {
66 return;
67 }
68 if (this.ds != null) {
69 ds.send(packet);
70 }
71
72 }
73
74 public void close() {
75 address = null;
76 ds = null;
77 }
78
79 public int getPort() {
80 return port;
81 }
82
83 @Override
84 public void write(int b) throws IOException {
85 baos.write(b);
86 }
87
88 int getSendBufferSize() throws SocketException {
89 return ds.getSendBufferSize();
90 }
91 }