View Javadoc
1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, 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 v2.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 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   * SyslogOutputStream is a wrapper around the {@link DatagramSocket} class so
31   * that it behaves like an {@link OutputStream}.
32   */
33  public class SyslogOutputStream extends OutputStream {
34  
35      /**
36       * The maximum length after which we discard the existing string buffer and
37       * start anew.
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          // This stream only sends datagrams to the syslog host. Connecting the socket removes it from
52          // the list of unconnected (wildcard) UDP listeners reported by tools like `ss -ulnp`.
53          // See https://github.com/qos-ch/logback/issues/939
54          try {
55              this.ds.connect(new InetSocketAddress(address, port));
56          } catch (SocketException e) {
57              // connecting may fail, e.g. if the network is not yet available. In that case
58              // fall back to an unconnected socket, i.e. the behavior prior to issue 939.
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       * Returns the exception thrown when connecting the underlying socket to the
76       * syslog host, or null if the connection succeeded.
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          // clean up for next round
93          if (baos.size() > MAX_LEN) {
94              baos = new ByteArrayOutputStream();
95          } else {
96              baos.reset();
97          }
98  
99          // after a failure, it can happen that bytes.length is zero
100         // in that case, there is no point in sending out an empty message/
101         if (bytes.length == 0) {
102             return;
103         }
104         if (this.ds != null) {
105             try {
106                 ds.send(packet);
107             } catch (PortUnreachableException e) {
108                 // On a connected socket, an ICMP port unreachable message triggered by a
109                 // previously sent datagram is reported on the next send, in which case the
110                 // current packet is not sent. Retry once so that the current packet is not lost,
111                 // as was the case with unconnected sockets. Should the retry fail as well, the
112                 // exception propagates to the caller.
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 }