| 1 | package net.minecraft.util.profiling.jfr;
|
| 2 |
|
| 3 | import com.mojang.logging.LogUtils;
|
| 4 | import java.nio.file.Files;
|
| 5 | import java.nio.file.Path;
|
| 6 | import java.nio.file.StandardOpenOption;
|
| 7 | import java.util.function.Supplier;
|
| 8 | import net.minecraft.server.Bootstrap;
|
| 9 | import net.minecraft.util.profiling.jfr.parse.JfrStatsParser;
|
| 10 | import net.minecraft.util.profiling.jfr.parse.JfrStatsResult;
|
| 11 | import org.apache.commons.lang3.StringUtils;
|
| 12 | import org.jspecify.annotations.Nullable;
|
| 13 | import org.slf4j.Logger;
|
| 14 |
|
| 15 | public class SummaryReporter {
|
| 16 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 17 | private final Runnable onDeregistration;
|
| 18 |
|
| 19 | protected SummaryReporter(final Runnable onDeregistration) {
|
| 20 | this.onDeregistration = onDeregistration;
|
| 21 | }
|
| 22 |
|
| 23 | public void recordingStopped(final @Nullable Path result) {
|
| 24 | if (result != null) {
|
| 25 | this.onDeregistration.run();
|
| 26 | infoWithFallback(() -> "Dumped flight recorder profiling to " + result);
|
| 27 |
|
| 28 | JfrStatsResult statsResult;
|
| 29 | try {
|
| 30 | statsResult = JfrStatsParser.parse(result);
|
| 31 | } catch (Throwable t) {
|
| 32 | warnWithFallback(() -> "Failed to parse JFR recording", t);
|
| 33 | return;
|
| 34 | }
|
| 35 |
|
| 36 | try {
|
| 37 | infoWithFallback(statsResult::asJson);
|
| 38 | Path jsonReport = result.resolveSibling("jfr-report-" + StringUtils.substringBefore(result.getFileName().toString(), ".jfr") + ".json");
|
| 39 | Files.writeString(jsonReport, statsResult.asJson(), StandardOpenOption.CREATE);
|
| 40 | infoWithFallback(() -> "Dumped recording summary to " + jsonReport);
|
| 41 | } catch (Throwable t) {
|
| 42 | warnWithFallback(() -> "Failed to output JFR report", t);
|
| 43 | }
|
| 44 | }
|
| 45 | }
|
| 46 |
|
| 47 | private static void infoWithFallback(final Supplier<String> message) {
|
| 48 | if (LogUtils.isLoggerActive()) {
|
| 49 | LOGGER.info("{}", message.get());
|
| 50 | } else {
|
| 51 | Bootstrap.realStdoutPrintln(message.get());
|
| 52 | }
|
| 53 | }
|
| 54 |
|
| 55 | private static void warnWithFallback(final Supplier<String> message, final Throwable t) {
|
| 56 | if (LogUtils.isLoggerActive()) {
|
| 57 | LOGGER.warn("{}", message.get(), t);
|
| 58 | } else {
|
| 59 | Bootstrap.realStdoutPrintln(message.get());
|
| 60 | t.printStackTrace(Bootstrap.STDOUT);
|
| 61 | }
|
| 62 | }
|
| 63 | }
|
| 64 |
|