
dev.lajoscseppento.ruthless.plugin.logging.impl.BuildLogWriter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of ruthless-plugin Show documentation
Show all versions of ruthless-plugin Show documentation
Ruthless conventions for Gradle projects to keep them DRY
package dev.lajoscseppento.ruthless.plugin.logging.impl;
import dev.lajoscseppento.ruthless.plugin.logging.RuthlessLogger;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import lombok.Getter;
import lombok.NonNull;
import org.gradle.api.GradleException;
/**
* Writer for build logs. The build log may be closed and opened during writing several times,
* because new events may or may not arrive after the first and definite sign of closing the file.
*
*
* - Opens the file upon object creation, truncating it if already exists
*
- Flushes output on each
print*
call
* - Reopens the file on any
print*
close if it was previously closed. Make sure to
* always call {@link #close()} after the last print*
call to avoid leaks.
*
*/
class BuildLogWriter {
private final RuthlessLogger logger;
@Getter private final Path file;
private volatile PrintWriter writer;
private final Object lock = new Object();
BuildLogWriter(@NonNull Path file) {
this.logger = RuthlessLogger.create(getClass(), "ruthless-logging");
this.file = file.toAbsolutePath();
this.writer = null;
ensureOpen(false);
}
private void ensureOpen(boolean append) {
synchronized (lock) {
if (writer == null) {
logger.debug("Opening build log writer: {} (append={})", file, append);
try {
writer =
new PrintWriter(
new OutputStreamWriter(
new FileOutputStream(file.toFile(), append), StandardCharsets.UTF_8),
false);
} catch (Exception ex) {
String msg = String.format("Failed to create writer for %s: %s", file, ex.getMessage());
throw new GradleException(msg, ex);
}
}
}
}
void close() {
synchronized (lock) {
if (writer != null) {
logger.debug("Closing build log writer: {}", file);
writer.close();
writer = null;
}
}
}
void print(Object obj) {
synchronized (lock) {
ensureOpen(true);
writer.print(obj);
writer.flush();
}
}
void println() {
synchronized (lock) {
ensureOpen(true);
writer.println();
writer.flush();
}
}
void println(Object obj) {
synchronized (lock) {
ensureOpen(true);
writer.println(obj);
writer.flush();
}
}
void printf(String format, Object... args) {
synchronized (lock) {
ensureOpen(true);
writer.printf(format, args);
writer.flush();
}
}
void printStackTrace(Throwable throwable) {
synchronized (lock) {
ensureOpen(true);
throwable.printStackTrace(writer);
writer.flush();
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy