1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.net;
18
19 import org.apache.logging.log4j.core.Layout;
20 import org.apache.logging.log4j.core.appender.ManagerFactory;
21 import org.apache.logging.log4j.core.helpers.Strings;
22
23 import java.io.OutputStream;
24 import java.io.Serializable;
25 import java.net.InetAddress;
26 import java.net.UnknownHostException;
27 import java.util.HashMap;
28 import java.util.Map;
29
30
31
32
33 public class DatagramSocketManager extends AbstractSocketManager {
34
35 private static final DatagramSocketManagerFactory FACTORY = new DatagramSocketManagerFactory();
36
37
38
39
40
41
42
43
44
45
46 protected DatagramSocketManager(final String name, final OutputStream os, final InetAddress address, final String host,
47 final int port, final Layout<? extends Serializable> layout) {
48 super(name, os, address, host, port, layout);
49 }
50
51
52
53
54
55
56
57
58 public static DatagramSocketManager getSocketManager(final String host, final int port, final Layout<? extends Serializable> layout) {
59 if (Strings.isEmpty(host)) {
60 throw new IllegalArgumentException("A host name is required");
61 }
62 if (port <= 0) {
63 throw new IllegalArgumentException("A port value is required");
64 }
65 return (DatagramSocketManager) getManager("UDP:" + host + ":" + port, new FactoryData(host, port, layout),
66 FACTORY);
67 }
68
69
70
71
72
73
74
75 @Override
76 public Map<String, String> getContentFormat()
77 {
78 final Map<String, String> result = new HashMap<String, String>(super.getContentFormat());
79 result.put("protocol", "udp");
80 result.put("direction", "out");
81
82 return result;
83 }
84
85
86
87
88 private static class FactoryData {
89 private final String host;
90 private final int port;
91 private final Layout<? extends Serializable> layout;
92
93 public FactoryData(final String host, final int port, final Layout<? extends Serializable> layout) {
94 this.host = host;
95 this.port = port;
96 this.layout = layout;
97 }
98 }
99
100
101
102
103 private static class DatagramSocketManagerFactory implements ManagerFactory<DatagramSocketManager, FactoryData> {
104
105 @Override
106 public DatagramSocketManager createManager(final String name, final FactoryData data) {
107 InetAddress address;
108 final OutputStream os = new DatagramOutputStream(data.host, data.port, data.layout.getHeader(),
109 data.layout.getFooter());
110 try {
111 address = InetAddress.getByName(data.host);
112 } catch (final UnknownHostException ex) {
113 LOGGER.error("Could not find address of " + data.host, ex);
114 return null;
115 }
116 return new DatagramSocketManager(name, os, address, data.host, data.port, data.layout);
117 }
118 }
119 }