Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 6c61f360 authored by Justin Weir's avatar Justin Weir
Browse files

Move logging to background thread in LogBuffer

To avoid checking log level settings on the main thread, which can cause jank, move the settings check and logging to a background thread. During manually testing with both the original mechanism and the background thread, messages still appeared in the console with the exact same timestamp (to the millisecond). Nothing I did on the phone was able to get the background thread's BlockingQueue to ever hold more than 3 messages at any given time.

Bug: 221419865
Test: Manually verified messages still logged and BlockingQueue had sufficient capacity
Change-Id: If230e09674dcf1dd7e7b1026e71717f982c5b3d2
parent 8e375e4c
Loading
Loading
Loading
Loading
+26 −0
Original line number Diff line number Diff line
@@ -23,6 +23,9 @@ import java.io.PrintWriter
import java.text.SimpleDateFormat
import java.util.ArrayDeque
import java.util.Locale
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue
import kotlin.concurrent.thread

/**
 * A simple ring buffer of recyclable log messages
@@ -81,6 +84,19 @@ class LogBuffer @JvmOverloads constructor(
    }

    private val buffer: ArrayDeque<LogMessageImpl> = ArrayDeque()
    private val echoMessageQueue: BlockingQueue<LogMessageImpl> = ArrayBlockingQueue(poolSize)

    init {
        thread(start = true, priority = Thread.NORM_PRIORITY) {
            try {
                while (true) {
                    echoToDesiredEndpoints(echoMessageQueue.take())
                }
            } catch (e: InterruptedException) {
                Thread.currentThread().interrupt()
            }
        }
    }

    var frozen = false
        private set
@@ -176,6 +192,16 @@ class LogBuffer @JvmOverloads constructor(
            buffer.removeFirst()
        }
        buffer.add(message as LogMessageImpl)
        // Log in the background thread only if it has capacity to avoid blocking this thread
        if (echoMessageQueue.remainingCapacity() > 0) {
            echoMessageQueue.put(message)
        } else {
            echoToDesiredEndpoints(message)
        }
    }

    /** Sends message to echo after determining whether to use Logcat and/or systrace. */
    private fun echoToDesiredEndpoints(message: LogMessageImpl) {
        val includeInLogcat = logcatEchoTracker.isBufferLoggable(name, message.level) ||
                logcatEchoTracker.isTagLoggable(message.tag, message.level)
        echo(message, toLogcat = includeInLogcat, toSystrace = systrace)