View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
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   * SyslogOutputStream is a wrapper around the {@link DatagramSocket} class so
27   * that it behaves like an {@link OutputStream}.
28   */
29  public class SyslogOutputStream extends OutputStream {
30  
31      /**
32       * The maximum length after which we discard the existing string buffer and
33       * start anew.
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          // clean up for next round
57          if (baos.size() > MAX_LEN) {
58              baos = new ByteArrayOutputStream();
59          } else {
60              baos.reset();
61          }
62  
63          // after a failure, it can happen that bytes.length is zero
64          // in that case, there is no point in sending out an empty message/
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  }