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,
43 SocketException {
44 this.address = InetAddress.getByName(syslogHost);
45 this.port = port;
46 this.ds = new DatagramSocket();
47 }
48
49 public void write(byte[] byteArray, int offset, int len) throws IOException {
50 baos.write(byteArray, offset, len);
51 }
52
53 public void flush() throws IOException {
54 byte[] bytes = baos.toByteArray();
55 DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address,
56 port);
57
58
59 if (baos.size() > MAX_LEN) {
60 baos = new ByteArrayOutputStream();
61 } else {
62 baos.reset();
63 }
64
65
66
67 if(bytes.length == 0) {
68 return;
69 }
70 if (this.ds != null) {
71 ds.send(packet);
72 }
73
74 }
75
76 public void close() {
77 address = null;
78 ds = null;
79 }
80
81 public int getPort() {
82 return port;
83 }
84
85 @Override
86 public void write(int b) throws IOException {
87 baos.write(b);
88 }
89
90 }