| 1 | package net.minecraft.client.telemetry;
|
| 2 |
|
| 3 | import com.mojang.logging.LogUtils;
|
| 4 | import java.io.IOException;
|
| 5 | import java.nio.channels.FileChannel;
|
| 6 | import java.nio.file.Path;
|
| 7 | import java.time.Clock;
|
| 8 | import java.time.LocalDate;
|
| 9 | import java.util.Optional;
|
| 10 | import java.util.concurrent.CompletableFuture;
|
| 11 | import net.fabricmc.api.EnvType;
|
| 12 | import net.fabricmc.api.Environment;
|
| 13 | import net.minecraft.util.Util;
|
| 14 | import net.minecraft.util.eventlog.EventLogDirectory;
|
| 15 | import net.minecraft.util.eventlog.EventLogDirectory.RawFile;
|
| 16 | import org.jspecify.annotations.Nullable;
|
| 17 | import org.slf4j.Logger;
|
| 18 |
|
| 19 | @Environment(EnvType.CLIENT)
|
| 20 | public class TelemetryLogManager implements AutoCloseable {
|
| 21 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 22 | private static final String RAW_EXTENSION = ".json";
|
| 23 | private static final int EXPIRY_DAYS = 7;
|
| 24 | private final EventLogDirectory directory;
|
| 25 | private @Nullable CompletableFuture<Optional<TelemetryEventLog>> sessionLog;
|
| 26 |
|
| 27 | private TelemetryLogManager(final EventLogDirectory directory) {
|
| 28 | this.directory = directory;
|
| 29 | }
|
| 30 |
|
| 31 | public static CompletableFuture<Optional<TelemetryLogManager>> open(final Path root) {
|
| 32 | return CompletableFuture.supplyAsync(() -> {
|
| 33 | try {
|
| 34 | EventLogDirectory directory = EventLogDirectory.open(root, ".json");
|
| 35 | directory.listFiles().prune(LocalDate.now(Clock.systemDefaultZone()), 7).compressAll();
|
| 36 | return Optional.of(new TelemetryLogManager(directory));
|
| 37 | } catch (Exception e) {
|
| 38 | LOGGER.error("Failed to create telemetry log manager", e);
|
| 39 | return Optional.empty();
|
| 40 | }
|
| 41 | }, Util.backgroundExecutor());
|
| 42 | }
|
| 43 |
|
| 44 | public CompletableFuture<Optional<TelemetryEventLogger>> openLogger() {
|
| 45 | if (this.sessionLog == null) {
|
| 46 | this.sessionLog = CompletableFuture.supplyAsync(() -> {
|
| 47 | try {
|
| 48 | RawFile file = this.directory.createNewFile(LocalDate.now(Clock.systemDefaultZone()));
|
| 49 | FileChannel channel = file.openChannel();
|
| 50 | return Optional.of(new TelemetryEventLog(channel, Util.backgroundExecutor()));
|
| 51 | } catch (IOException e) {
|
| 52 | LOGGER.error("Failed to open channel for telemetry event log", e);
|
| 53 | return Optional.empty();
|
| 54 | }
|
| 55 | }, Util.backgroundExecutor());
|
| 56 | }
|
| 57 |
|
| 58 | return this.sessionLog.thenApply(log -> log.map(TelemetryEventLog::logger));
|
| 59 | }
|
| 60 |
|
| 61 | @Override
|
| 62 | public void close() {
|
| 63 | if (this.sessionLog != null) {
|
| 64 | this.sessionLog.thenAccept(log -> log.ifPresent(TelemetryEventLog::close));
|
| 65 | }
|
| 66 | }
|
| 67 | }
|
| 68 |
|