Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #5232: ConsoleLogger overwrites local log file for each line write~ #5275

Closed
wants to merge 7 commits into from
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,27 @@ package org.oppia.android.util.logging

import android.content.Context
import android.util.Log
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.oppia.android.util.locale.OppiaLocale
import org.oppia.android.util.threading.BlockingDispatcher
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStreamWriter
import java.io.PrintWriter
import javax.inject.Inject
import javax.inject.Singleton

/** Wrapper class for Android logcat and file logging. All logs in the app should use this class. */
@Singleton
class ConsoleLogger @Inject constructor(
context: Context,
@BlockingDispatcher private val blockingDispatcher: CoroutineDispatcher,
@EnableConsoleLog private val enableConsoleLog: Boolean,
@EnableFileLog private val enableFileLog: Boolean,
@GlobalLogLevel private val globalLogLevel: LogLevel,
private val machineLocale: OppiaLocale.MachineLocale
) {
private val blockingScope = CoroutineScope(blockingDispatcher)
private val logDirectory = File(context.filesDir, "oppia_app.log")
private val logStream = PrintWriter(
OutputStreamWriter(FileOutputStream(logDirectory, true), Charsets.UTF_8)
)

/** Logs a verbose message with the specified tag. */
fun v(tag: String, msg: String) {
Expand Down Expand Up @@ -94,17 +94,17 @@ class ConsoleLogger @Inject constructor(
Log.println(logLevel.logLevel, tag, fullLog)
}
if (enableFileLog) {
logToFileInBackground(
logStream.println(
"${machineLocale.computeCurrentTimeString()}\t${logLevel.name}/$tag: $fullLog"
)
logStream.flush()
}
}

/**
* Writes the specified text line to file in a background thread to ensure that saving messages don't block the main
* thread. A blocking dispatcher is used to ensure messages are written in order.
* Closes the log stream when the logger is no longer needed.
*/
private fun logToFileInBackground(text: String) {
blockingScope.launch { logDirectory.printWriter().use { out -> out.println(text) } }
fun close() {
logStream.close()
}
}
Loading