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
24 import org.apache.logging.log4j.core.Layout;
25 import org.apache.logging.log4j.core.LogEvent;
26 import org.apache.logging.log4j.core.config.Node;
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 = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true)
34 public final class SerializedLayout extends AbstractLayout<LogEvent> {
35
36 private static final long serialVersionUID = 1L;
37
38 private static byte[] serializedHeader;
39
40 static {
41 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
42 try {
43 final ObjectOutputStream oos = new ObjectOutputStream(baos);
44 oos.close();
45 serializedHeader = baos.toByteArray();
46 } catch (final Exception ex) {
47 LOGGER.error("Unable to generate Object stream header", ex);
48 }
49 }
50
51 private SerializedLayout() {
52 super(null, null);
53 }
54
55
56
57
58
59
60
61 @Override
62 public byte[] toByteArray(final LogEvent event) {
63 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
64 try {
65 final ObjectOutputStream oos = new PrivateObjectOutputStream(baos);
66 try {
67 oos.writeObject(event);
68 oos.reset();
69 } finally {
70 oos.close();
71 }
72 } catch (final IOException ioe) {
73 LOGGER.error("Serialization of LogEvent failed.", ioe);
74 }
75 return baos.toByteArray();
76 }
77
78
79
80
81
82
83
84 @Override
85 public LogEvent toSerializable(final LogEvent event) {
86 return event;
87 }
88
89
90
91
92
93 @PluginFactory
94 public static SerializedLayout createLayout() {
95 return new SerializedLayout();
96 }
97
98 @Override
99 public byte[] getHeader() {
100 return serializedHeader;
101 }
102
103
104
105
106
107 @Override
108 public String getContentType() {
109 return "application/octet-stream";
110 }
111
112
113
114
115 private class PrivateObjectOutputStream extends ObjectOutputStream {
116
117 public PrivateObjectOutputStream(final OutputStream os) throws IOException {
118 super(os);
119 }
120
121 @Override
122 protected void writeStreamHeader() {
123 }
124 }
125 }