1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.appender;
18
19 import org.apache.logging.log4j.core.Layout;
20
21 import java.io.IOException;
22 import java.io.OutputStream;
23
24
25
26
27
28 public class OutputStreamManager extends AbstractManager {
29
30 private volatile OutputStream os;
31
32 private final byte[] footer;
33 private final byte[] header;
34
35 protected OutputStreamManager(final OutputStream os, final String streamName, final Layout layout) {
36 super(streamName);
37 this.os = os;
38 if (layout != null) {
39 this.footer = layout.getFooter();
40 this.header = layout.getHeader();
41 if (this.header != null) {
42 try {
43 this.os.write(header, 0, header.length);
44 } catch (final IOException ioe) {
45 LOGGER.error("Unable to write header", ioe);
46 }
47 }
48 } else {
49 this.footer = null;
50 this.header = null;
51 }
52 }
53
54
55
56
57
58
59
60
61
62
63 public static <T> OutputStreamManager getManager(final String name, final T data,
64 final ManagerFactory<? extends OutputStreamManager, T> factory) {
65 return AbstractManager.getManager(name, factory, data);
66 }
67
68
69
70
71 @Override
72 public void releaseSub() {
73 if (footer != null) {
74 write(footer);
75 }
76 close();
77 }
78
79
80
81
82
83 public boolean isOpen() {
84 return getCount() > 0;
85 }
86
87 protected OutputStream getOutputStream() {
88 return os;
89 }
90
91 protected void setOutputStream(final OutputStream os) {
92 if (header != null) {
93 try {
94 os.write(header, 0, header.length);
95 this.os = os;
96 } catch (final IOException ioe) {
97 LOGGER.error("Unable to write header", ioe);
98 }
99 } else {
100 this.os = os;
101 }
102 }
103
104
105
106
107
108
109
110
111
112 protected synchronized void write(final byte[] bytes, final int offset, final int length) {
113
114 try {
115 os.write(bytes, offset, length);
116 } catch (final IOException ex) {
117 final String msg = "Error writing to stream " + getName();
118 throw new AppenderRuntimeException(msg, ex);
119 }
120 }
121
122
123
124
125
126
127
128 protected void write(final byte[] bytes) {
129 write(bytes, 0, bytes.length);
130 }
131
132 protected void close() {
133 OutputStream stream = os;
134 if (stream == System.out || stream == System.err) {
135 return;
136 }
137 try {
138 stream.close();
139 } catch (final IOException ex) {
140 LOGGER.error("Unable to close stream " + getName() + ". " + ex);
141 }
142 }
143
144
145
146
147 public void flush() {
148 try {
149 os.flush();
150 } catch (final IOException ex) {
151 final String msg = "Error flushing stream " + getName();
152 throw new AppenderRuntimeException(msg, ex);
153 }
154 }
155 }