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