Skip to content

Commit

Permalink
[Refactor] Fix creating logger in a remote service
Browse files Browse the repository at this point in the history
In a remote service, the logger behaves like Android logger.

Signed-off-by: Muntashir Al-Islam <muntashirakon@riseup.net>
  • Loading branch information
MuntashirAkon committed Jul 6, 2024
1 parent 8ba350f commit 544d927
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,14 @@ public class Log extends Logger {

static {
DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ROOT);
LOG_FILE = new File(getLoggingDirectory(), "am.log");
File logFile;
try {
logFile = new File(getLoggingDirectory(), "am.log");
} catch (SecurityException e) {
// Remote side doesn't have a logging directory
logFile = null;
}
LOG_FILE = logFile;
try {
sInstance = new Log();
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,18 @@ public static File getLoggingDirectory() {
return FileUtils.getCachePath();
}

@Nullable
private final PrintWriter mWriter;

private boolean mIsClosed;

protected Logger(File logFile, boolean append) throws IOException {
mWriter = new PrintWriter(new BufferedWriter(new FileWriter(logFile, append)));
protected Logger(@Nullable File logFile, boolean append) throws IOException {
if (logFile != null) {
mWriter = new PrintWriter(new BufferedWriter(new FileWriter(logFile, append)));
} else mWriter = null;
}

protected Logger(PrintWriter printWriter) throws IOException {
protected Logger(@Nullable PrintWriter printWriter) throws IOException {
mWriter = printWriter;
}

Expand All @@ -41,6 +44,10 @@ public void println(@Nullable Object message) {

@CallSuper
public void println(@Nullable Object message, @Nullable Throwable tr) {
if (mWriter == null) {
// Do nothing
return;
}
synchronized (mWriter) {
mWriter.println(message);
if (tr != null) {
Expand All @@ -55,15 +62,17 @@ public void println(@Nullable Object message, @Nullable Throwable tr) {
@CallSuper
@Override
public void close() {
mWriter.flush();
mWriter.close();
if (mWriter != null) {
mWriter.flush();
mWriter.close();
}
mIsClosed = true;
}

@Override
protected void finalize() {
// Closing is mandatory in order to make sure the logs are written correctly
if (!mIsClosed) {
if (!mIsClosed && mWriter != null) {
mWriter.flush();
mWriter.close();
}
Expand Down

0 comments on commit 544d927

Please sign in to comment.