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 org.apache.logging.log4j.core.LogEvent;
20 import org.apache.logging.log4j.core.config.plugins.Plugin;
21 import org.apache.logging.log4j.core.config.plugins.PluginFactory;
22
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.io.ObjectOutputStream;
26 import java.io.OutputStream;
27
28
29
30
31 @Plugin(name = "SerializedLayout", type = "Core", elementType = "layout", printObject = true)
32 public final class SerializedLayout extends AbstractLayout<LogEvent> {
33
34 private static byte[] header;
35
36 static {
37 ByteArrayOutputStream baos = new ByteArrayOutputStream();
38 try {
39 ObjectOutputStream oos = new ObjectOutputStream(baos);
40 oos.close();
41 header = baos.toByteArray();
42 } catch (Exception ex) {
43 LOGGER.error("Unable to generate Object stream header", ex);
44 }
45 }
46
47 private SerializedLayout() {
48 }
49
50
51
52
53
54
55
56 public byte[] toByteArray(final LogEvent event) {
57 ByteArrayOutputStream baos = new ByteArrayOutputStream();
58 try {
59 ObjectOutputStream oos = new PrivateObjectOutputStream(baos);
60 try {
61 oos.writeObject(event);
62 } finally {
63 oos.close();
64 }
65 } catch (IOException ioe) {
66 LOGGER.error("Serialization of LogEvent failed.", ioe);
67 }
68 return baos.toByteArray();
69 }
70
71
72
73
74
75
76
77 public LogEvent toSerializable(final LogEvent event) {
78 return event;
79 }
80
81
82
83
84
85 @PluginFactory
86 public static SerializedLayout createLayout() {
87
88 return new SerializedLayout();
89 }
90
91 @Override
92 public byte[] getHeader() {
93 return header;
94 }
95
96
97
98
99 private class PrivateObjectOutputStream extends ObjectOutputStream {
100
101 public PrivateObjectOutputStream(OutputStream os) throws IOException {
102 super(os);
103 }
104
105 @Override
106 protected void writeStreamHeader() {
107 }
108 }
109 }