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