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