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