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