View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, 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 that it
27   * 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,
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      // clean up for next round
59      if (baos.size() > MAX_LEN) {
60        baos = new ByteArrayOutputStream();
61      } else {
62        baos.reset();
63      }
64      
65      // after a failure, it can happen that bytes.length is zero
66      // in that case, there is no point in sending out an empty message/
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  }