Fix the apm-jdk-threadpool-plugin does not work in certain scenarios (#556)

This commit is contained in:
xiaqi1210 2023-06-16 21:26:34 +08:00 committed by GitHub
parent 6621f82739
commit 35388ac062
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 40 additions and 30 deletions

View File

@ -18,6 +18,10 @@
package org.apache.skywalking.apm.agent.core.logging.core;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.conf.Constants;
import org.apache.skywalking.apm.util.RunnableWithExceptionProtection;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
@ -30,13 +34,8 @@ import java.util.Comparator;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.apache.skywalking.apm.agent.core.boot.DefaultNamedThreadFactory;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.conf.Constants;
import org.apache.skywalking.apm.util.RunnableWithExceptionProtection;
/**
* The <code>FileWriter</code> support async file output, by using a queue as buffer.
@ -63,31 +62,42 @@ public class FileWriter implements IWriter {
private FileWriter() {
logBuffer = new ArrayBlockingQueue(1024);
final ArrayList<String> outputLogs = new ArrayList<String>(200);
Executors.newSingleThreadScheduledExecutor(new DefaultNamedThreadFactory("LogFileWriter"))
.scheduleAtFixedRate(new RunnableWithExceptionProtection(new Runnable() {
@Override
public void run() {
try {
logBuffer.drainTo(outputLogs);
for (String log : outputLogs) {
writeToFile(log + Constants.LINE_SEPARATOR);
}
try {
if (fileOutputStream != null) {
fileOutputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
} finally {
outputLogs.clear();
}
}
}, new RunnableWithExceptionProtection.CallbackWhenException() {
@Override
public void handle(Throwable t) {
}
}), 0, 1, TimeUnit.SECONDS);
Thread logFlusherThread = new Thread(new RunnableWithExceptionProtection(new Runnable() {
@Override
public void run() {
while (true) {
// flush log to file
try {
logBuffer.drainTo(outputLogs);
for (String log : outputLogs) {
writeToFile(log + Constants.LINE_SEPARATOR);
}
try {
if (fileOutputStream != null) {
fileOutputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
} finally {
outputLogs.clear();
}
// flush log once per second
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
}
}
}
}, new RunnableWithExceptionProtection.CallbackWhenException() {
@Override
public void handle(Throwable t) {
}
}), "SkywalkingAgent-LogFileWriter");
logFlusherThread.start();
}
/**