1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.layout;
18
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.ObjectOutputStream;
22 import java.io.OutputStream;
23 import java.util.HashMap;
24 import java.util.Map;
25
26 import org.apache.logging.log4j.core.LogEvent;
27 import org.apache.logging.log4j.core.config.plugins.Plugin;
28 import org.apache.logging.log4j.core.config.plugins.PluginFactory;
29
30
31
32
33 @Plugin(name = "SerializedLayout", category = "Core", elementType = "layout", printObject = true)
34 public final class SerializedLayout extends AbstractLayout<LogEvent> {
35
36 private static byte[] serializedHeader;
37
38 static {
39 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
40 try {
41 final ObjectOutputStream oos = new ObjectOutputStream(baos);
42 oos.close();
43 serializedHeader = baos.toByteArray();
44 } catch (final Exception ex) {
45 LOGGER.error("Unable to generate Object stream header", ex);
46 }
47 }
48
49 private SerializedLayout() {
50 }
51
52
53
54
55
56
57
58 @Override
59 public byte[] toByteArray(final LogEvent event) {
60 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
61 try {
62 final ObjectOutputStream oos = new PrivateObjectOutputStream(baos);
63 try {
64 oos.writeObject(event);
65 oos.reset();
66 } finally {
67 oos.close();
68 }
69 } catch (final IOException ioe) {
70 LOGGER.error("Serialization of LogEvent failed.", ioe);
71 }
72 return baos.toByteArray();
73 }
74
75
76
77
78
79
80
81 @Override
82 public LogEvent toSerializable(final LogEvent event) {
83 return event;
84 }
85
86
87
88
89
90 @PluginFactory
91 public static SerializedLayout createLayout() {
92 return new SerializedLayout();
93 }
94
95 @Override
96 public byte[] getHeader() {
97 return serializedHeader;
98 }
99
100
101
102
103
104 @Override
105 public Map<String, String> getContentFormat() {
106 return new HashMap<String, String>();
107 }
108
109
110
111
112
113 @Override
114 public String getContentType() {
115 return "application/octet-stream";
116 }
117
118
119
120
121 private class PrivateObjectOutputStream extends ObjectOutputStream {
122
123 public PrivateObjectOutputStream(final OutputStream os) throws IOException {
124 super(os);
125 }
126
127 @Override
128 protected void writeStreamHeader() {
129 }
130 }
131 }