1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.systemui.log.core 18 19 import android.util.Log 20 import com.android.systemui.log.LogMessageImpl 21 22 /** 23 * A simple implementation of [MessageBuffer] that forwards messages to [android.util.Log] 24 * immediately. This defeats the intention behind [LogBuffer] and should only be used when 25 * [LogBuffer]s are unavailable in a certain context. 26 */ 27 class LogcatOnlyMessageBuffer( 28 val targetLogLevel: LogLevel, 29 ) : MessageBuffer { 30 private val singleMessage = LogMessageImpl.Factory.create() 31 private var isObtained: Boolean = false 32 33 @Synchronized obtainnull34 override fun obtain( 35 tag: String, 36 level: LogLevel, 37 messagePrinter: MessagePrinter, 38 exception: Throwable?, 39 ): LogMessage { 40 if (isObtained) { 41 throw UnsupportedOperationException( 42 "Message has already been obtained. Call order is incorrect." 43 ) 44 } 45 46 singleMessage.reset(tag, level, System.currentTimeMillis(), messagePrinter, exception) 47 isObtained = true 48 return singleMessage 49 } 50 51 @Synchronized commitnull52 override fun commit(message: LogMessage) { 53 if (singleMessage != message) { 54 throw IllegalArgumentException("Message argument is not the expected message.") 55 } 56 if (!isObtained) { 57 throw UnsupportedOperationException( 58 "Message has not been obtained. Call order is incorrect." 59 ) 60 } 61 62 if (message.level >= targetLogLevel) { 63 val strMessage = message.messagePrinter(message) 64 when (message.level) { 65 LogLevel.VERBOSE -> Log.v(message.tag, strMessage, message.exception) 66 LogLevel.DEBUG -> Log.d(message.tag, strMessage, message.exception) 67 LogLevel.INFO -> Log.i(message.tag, strMessage, message.exception) 68 LogLevel.WARNING -> Log.w(message.tag, strMessage, message.exception) 69 LogLevel.ERROR -> Log.e(message.tag, strMessage, message.exception) 70 LogLevel.WTF -> Log.wtf(message.tag, strMessage, message.exception) 71 } 72 } 73 74 isObtained = false 75 } 76 } 77