1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.net;
15
16 import ch.qos.logback.core.util.CloseUtil;
17
18 import java.io.ByteArrayOutputStream;
19 import java.io.IOException;
20 import java.io.OutputStream;
21 import java.net.DatagramPacket;
22 import java.net.DatagramSocket;
23 import java.net.InetAddress;
24 import java.net.InetSocketAddress;
25 import java.net.PortUnreachableException;
26 import java.net.SocketException;
27 import java.net.UnknownHostException;
28
29
30
31
32
33 public class SyslogOutputStream extends OutputStream {
34
35
36
37
38
39 private static final int MAX_LEN = 1024;
40
41 private InetAddress address;
42 private DatagramSocket ds;
43 private ByteArrayOutputStream baos = new ByteArrayOutputStream();
44 final private int port;
45 private SocketException connectException;
46
47 public SyslogOutputStream(String syslogHost, int port) throws UnknownHostException, SocketException {
48 this.address = InetAddress.getByName(syslogHost);
49 this.port = port;
50 this.ds = new DatagramSocket();
51
52
53
54 try {
55 this.ds.connect(new InetSocketAddress(address, port));
56 } catch (SocketException e) {
57
58
59 this.connectException = e;
60 }
61 }
62
63 boolean isValidState() {
64 if(ds == null || baos == null || address == null) {
65 return false;
66 }
67 return true;
68 }
69
70 boolean isConnected() {
71 return ds != null && ds.isConnected();
72 }
73
74
75
76
77
78 SocketException getConnectException() {
79 return connectException;
80 }
81
82 public void write(byte[] byteArray, int offset, int len) throws IOException {
83 if(!isValidState()) return;
84 baos.write(byteArray, offset, len);
85 }
86
87 public void flush() throws IOException {
88 if(!isValidState()) return;
89 byte[] bytes = baos.toByteArray();
90 DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, port);
91
92
93 if (baos.size() > MAX_LEN) {
94 baos = new ByteArrayOutputStream();
95 } else {
96 baos.reset();
97 }
98
99
100
101 if (bytes.length == 0) {
102 return;
103 }
104 if (this.ds != null) {
105 try {
106 ds.send(packet);
107 } catch (PortUnreachableException e) {
108
109
110
111
112
113 ds.send(packet);
114 }
115 }
116
117 }
118
119 @Override
120 public void close() {
121 CloseUtil.closeQuietly(ds);
122 CloseUtil.closeQuietly(baos);
123 address = null;
124 ds = null;
125 baos = null;
126 }
127
128 public int getPort() {
129 return port;
130 }
131
132 @Override
133 public void write(int b) throws IOException {
134 baos.write(b);
135 }
136
137 int getSendBufferSize() throws SocketException {
138 return ds.getSendBufferSize();
139 }
140 }