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.app.tracing 18 19 import android.util.Log 20 21 /** 22 * Utility class used to log state changes easily in a track with a custom name. 23 * 24 * Example of usage: 25 * ```kotlin 26 * class MyClass { 27 * val screenStateLogger = TraceStateLogger("Screen state") 28 * 29 * fun onTurnedOn() { screenStateLogger.log("on") } 30 * fun onTurnedOff() { screenStateLogger.log("off") } 31 * } 32 * ``` 33 * 34 * This creates a new slice in a perfetto trace only if the state is different than the previous 35 * one. 36 */ 37 class TraceStateLogger( 38 private val trackName: String, 39 private val logOnlyIfDifferent: Boolean = true, 40 private val instantEvent: Boolean = true, 41 private val logcat: Boolean = false, 42 ) { 43 44 private var previousValue: String? = null 45 46 /** If needed, logs the value to a track with name [trackName]. */ lognull47 fun log(newValue: String) { 48 if (instantEvent) { 49 instantForTrack(trackName, newValue) 50 } 51 if (logOnlyIfDifferent && previousValue == newValue) return 52 previousValue?.let { asyncTraceForTrackEnd(trackName, it, 0) } 53 asyncTraceForTrackBegin(trackName, newValue, 0) 54 if (logcat) { 55 Log.d(trackName, "newValue: $newValue") 56 } 57 previousValue = newValue 58 } 59 } 60