Skip to content

Commit a564cac

Browse files
committed
Capture stdout and stderr to log4j log (#50259)
This commit overrides the stdout and stderr print streams to be redirected to the main elasticsearch.log file. While the Elasticsearch project ensures stdout and stderr are not written to, the jdk or 3rd party libs may do this, which can be unexepected for users used to looking the elasticsearch log. closes #50156
1 parent 87b926a commit a564cac

File tree

3 files changed

+232
-0
lines changed

3 files changed

+232
-0
lines changed

server/src/main/java/org/elasticsearch/common/logging/LogConfigurator.java

+7
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,8 @@
4848

4949
import java.io.IOException;
5050
import java.io.InputStream;
51+
import java.io.PrintStream;
52+
import java.nio.charset.StandardCharsets;
5153
import java.nio.file.FileVisitOption;
5254
import java.nio.file.FileVisitResult;
5355
import java.nio.file.Files;
@@ -242,6 +244,11 @@ public FileVisitResult visitFile(final Path file, final BasicFileAttributes attr
242244
+ "log4j2.properties but will stop this behavior in 7.0. You should manually replace `%node_name` with "
243245
+ "`[%node_name]%marker ` in these locations:\n {}", deprecatedLocationsString);
244246
}
247+
248+
// Redirect stdout/stderr to log4j. While we ensure Elasticsearch code does not write to those streams,
249+
// third party libraries may do that
250+
System.setOut(new PrintStream(new LoggingOutputStream(LogManager.getLogger("stdout"), Level.INFO), false, StandardCharsets.UTF_8));
251+
System.setOut(new PrintStream(new LoggingOutputStream(LogManager.getLogger("stderr"), Level.WARN), false, StandardCharsets.UTF_8));
245252
}
246253

247254
private static void configureStatusLogger() {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/*
2+
* Licensed to Elasticsearch under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package org.elasticsearch.common.logging;
21+
22+
import org.apache.logging.log4j.Level;
23+
import org.apache.logging.log4j.Logger;
24+
25+
import java.io.IOException;
26+
import java.io.OutputStream;
27+
import java.nio.charset.StandardCharsets;
28+
import java.util.Arrays;
29+
30+
/**
31+
* A stream whose output is sent to the configured logger, line by line.
32+
*/
33+
class LoggingOutputStream extends OutputStream {
34+
/** The starting length of the buffer */
35+
static final int DEFAULT_BUFFER_LENGTH = 1024;
36+
37+
// limit a single log message to 64k
38+
static final int MAX_BUFFER_LENGTH = DEFAULT_BUFFER_LENGTH * 64;
39+
40+
class Buffer {
41+
42+
/** The buffer of bytes sent to the stream */
43+
byte[] bytes = new byte[DEFAULT_BUFFER_LENGTH];
44+
45+
/** Number of used bytes in the buffer */
46+
int used = 0;
47+
}
48+
49+
// each thread gets its own buffer so messages don't get garbled
50+
ThreadLocal<Buffer> threadLocal = ThreadLocal.withInitial(Buffer::new);
51+
52+
private final Logger logger;
53+
54+
private final Level level;
55+
56+
LoggingOutputStream(Logger logger, Level level) {
57+
this.logger = logger;
58+
this.level = level;
59+
}
60+
61+
@Override
62+
public void write(int b) throws IOException {
63+
if (threadLocal == null) {
64+
throw new IOException("buffer closed");
65+
}
66+
if (b == 0) return;
67+
if (b == '\n') {
68+
// always flush with newlines instead of adding to the buffer
69+
flush();
70+
return;
71+
}
72+
73+
Buffer buffer = threadLocal.get();
74+
75+
if (buffer.used == buffer.bytes.length) {
76+
if (buffer.bytes.length >= MAX_BUFFER_LENGTH) {
77+
// don't let the buffer get infinitely big
78+
flush();
79+
// we reset the buffer in flush so get the new instance
80+
buffer = threadLocal.get();
81+
} else {
82+
// extend the buffer
83+
buffer.bytes = Arrays.copyOf(buffer.bytes, 2 * buffer.bytes.length);
84+
}
85+
}
86+
87+
buffer.bytes[buffer.used++] = (byte) b;
88+
}
89+
90+
@Override
91+
public void flush() {
92+
Buffer buffer = threadLocal.get();
93+
if (buffer.used == 0) return;
94+
log(new String(buffer.bytes, 0, buffer.used, StandardCharsets.UTF_8));
95+
if (buffer.bytes.length != DEFAULT_BUFFER_LENGTH) {
96+
threadLocal.set(new Buffer()); // reset size
97+
} else {
98+
buffer.used = 0;
99+
}
100+
}
101+
102+
@Override
103+
public void close() {
104+
threadLocal = null;
105+
}
106+
107+
// pkg private for testing
108+
void log(String msg) {
109+
logger.log(level, msg);
110+
}
111+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
/*
2+
* Licensed to Elasticsearch under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package org.elasticsearch.common.logging;
21+
22+
import org.elasticsearch.test.ESTestCase;
23+
import org.junit.Before;
24+
25+
import java.io.IOException;
26+
import java.io.PrintStream;
27+
import java.nio.charset.StandardCharsets;
28+
import java.util.ArrayList;
29+
import java.util.List;
30+
31+
import static org.elasticsearch.common.logging.LoggingOutputStream.DEFAULT_BUFFER_LENGTH;
32+
import static org.elasticsearch.common.logging.LoggingOutputStream.MAX_BUFFER_LENGTH;
33+
import static org.hamcrest.Matchers.contains;
34+
import static org.hamcrest.Matchers.containsString;
35+
import static org.hamcrest.Matchers.equalTo;
36+
37+
public class LoggingOutputStreamTests extends ESTestCase {
38+
39+
class TestLoggingOutputStream extends LoggingOutputStream {
40+
List<String> lines = new ArrayList<>();
41+
42+
TestLoggingOutputStream() {
43+
super(null, null);
44+
}
45+
46+
@Override
47+
void log(String msg) {
48+
lines.add(msg);
49+
}
50+
}
51+
52+
TestLoggingOutputStream loggingStream;
53+
PrintStream printStream;
54+
55+
@Before
56+
public void createStream() {
57+
loggingStream = new TestLoggingOutputStream();
58+
printStream = new PrintStream(loggingStream, false, StandardCharsets.UTF_8);
59+
}
60+
61+
public void testEmptyLine() {
62+
printStream.println("");
63+
assertTrue(loggingStream.lines.isEmpty());
64+
printStream.flush();
65+
assertTrue(loggingStream.lines.isEmpty());
66+
}
67+
68+
public void testNull() {
69+
printStream.write(0);
70+
printStream.flush();
71+
assertTrue(loggingStream.lines.isEmpty());
72+
}
73+
74+
public void testFlushOnNewline() {
75+
printStream.println("hello");
76+
printStream.println("world");
77+
assertThat(loggingStream.lines, contains("hello", "world"));
78+
}
79+
80+
public void testBufferExtension() {
81+
String longStr = randomAlphaOfLength(DEFAULT_BUFFER_LENGTH);
82+
String extraLongStr = randomAlphaOfLength(DEFAULT_BUFFER_LENGTH + 1);
83+
printStream.println(longStr);
84+
assertThat(loggingStream.threadLocal.get().bytes.length, equalTo(DEFAULT_BUFFER_LENGTH));
85+
printStream.println(extraLongStr);
86+
assertThat(loggingStream.lines, contains(longStr, extraLongStr));
87+
assertThat(loggingStream.threadLocal.get().bytes.length, equalTo(DEFAULT_BUFFER_LENGTH));
88+
}
89+
90+
public void testMaxBuffer() {
91+
String longStr = randomAlphaOfLength(MAX_BUFFER_LENGTH);
92+
String extraLongStr = longStr + "OVERFLOW";
93+
printStream.println(longStr);
94+
printStream.println(extraLongStr);
95+
assertThat(loggingStream.lines, contains(longStr, longStr, "OVERFLOW"));
96+
}
97+
98+
public void testClosed() {
99+
loggingStream.close();
100+
IOException e = expectThrows(IOException.class, () -> loggingStream.write('a'));
101+
assertThat(e.getMessage(), containsString("buffer closed"));
102+
}
103+
104+
public void testThreadIsolation() throws Exception {
105+
printStream.print("from thread 1");
106+
Thread thread2 = new Thread(() -> {
107+
printStream.println("from thread 2");
108+
});
109+
thread2.start();
110+
thread2.join();
111+
printStream.flush();
112+
assertThat(loggingStream.lines, contains("from thread 2", "from thread 1"));
113+
}
114+
}

0 commit comments

Comments
 (0)