View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2009, 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.IOException;
17  import java.io.Writer;
18  import java.net.DatagramPacket;
19  import java.net.DatagramSocket;
20  import java.net.InetAddress;
21  import java.net.SocketException;
22  import java.net.UnknownHostException;
23  
24  /**
25   * SyslogWriter is a wrapper around the {@link DatagramSocket} class so that it
26   * behaves like a {@link Writer}.
27   */
28  public class SyslogWriter extends Writer {
29  
30    /**
31     * The maximum length after which we discard the existing string buffer and
32     * start anew.
33     */
34    private static final int MAX_LEN = 1024;
35  
36    private InetAddress address;
37    private DatagramSocket ds;
38    private StringBuffer buf = new StringBuffer();
39    final private int port;
40  
41    public SyslogWriter(String syslogHost, int port) throws UnknownHostException,
42        SocketException {
43      this.address = InetAddress.getByName(syslogHost);
44      this.port = port;
45      this.ds = new DatagramSocket();
46    }
47  
48    public void write(char[] charArray, int offset, int len) throws IOException {
49      buf.append(charArray, offset, len);
50    }
51  
52    public void write(String str) throws IOException {
53      buf.append(str);
54  
55    }
56  
57    public void flush() throws IOException {
58      byte[] bytes = buf.toString().getBytes();
59      DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address,
60          port);
61  
62      if (this.ds != null) {
63        ds.send(packet);
64      }
65      // clean up for next round
66      if (buf.length() > MAX_LEN) {
67        buf = new StringBuffer();
68      } else {
69        buf.setLength(0);
70      }
71    }
72  
73    public void close() {
74      address = null;
75      ds = null;
76    }
77  
78    public int getPort() {
79      return port;
80    }
81  
82  }